𝙎𝙌𝙇

[HackerRank] MySQL에서 median 중앙값 구하기 (Weather Observation Station 20)

콜라맛갈비 2023. 7. 7. 11:42
728x90

https://www.hackerrank.com/challenges/weather-observation-station-20/problem?isFullScreen=true 

 

Weather Observation Station 20 | HackerRank

Query the median of Northern Latitudes in STATION and round to 4 decimal places.

www.hackerrank.com

 

 

SELECT ROUND(LAT_N, 4)
FROM (
    SELECT LAT_N, RANK() OVER (ORDER BY LAT_N) AS RANKING
    FROM STATION
    ) A
WHERE RANKING = (
    SELECT FLOOR(COUNT(LAT_N)/2) + 1
    FROM STATION
    )

 

 

 

 

 

 

 

 

 

방법2) idx 열 사용

set @idx = -1;

select round(avg(LAT_N), 4)
from (select @idx := @idx + 1 as ROW_NUM, LAT_N
	from STATION
    order by LAT_N) as Sub
where Sub.ROW_NUM in (floor(@idx / 2), ceil(@idx / 2));

1. set @idx 변수 입력, -1로 저장

2. @idx는 행마다 +1씩 더해져 값이 출력 됨.

  0, 1 , 2, ...

3. @idx는 행의 가장 마지막 값이 출력됨

   ex. n행 있으면 @idx는 n-1 출력됨

 

 

 

 

방법3) percent_rank() 사용

select round(LAT_N, 4)
from (select LAT_N, percent_rank() over (order by LAT_N) as PERCENT
	from STATION) as Sub
where Sub.percent = 0.5
728x90

'𝙎𝙌𝙇' 카테고리의 다른 글

[HackerRank] Top Competitors  (0) 2023.07.10
[HackerRank] The Report  (0) 2023.07.07
[HackerRank] New Companies  (0) 2023.07.05
[MySQL] 문자열 합치기 : CONCAT_WS()  (0) 2023.06.30
[MySQL Workbench] csv 데이터 import 시간 줄이기  (0) 2023.06.02