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
직전 포스트에 이어서 중앙값 구하는 방법
[풀이]
- SET @ROW = -1; → 사용자 변수 초기화. 행 번호 붙이기 위해 -1부터 시작함.
- 내부 서브쿼리에서 LAT_N을 오름차순 정렬하고, 각 행에 @ROW := @ROW + 1로 번호 붙임 (0부터 시작).
- 바깥 쿼리에서 rn이 FLOOR(@ROW/2) 또는 CEIL(@ROW/2)인 행만 가져옴.
- 결과적으로 중앙값 위치에 있는 LAT_N 값 1개 또는 2개 추출
SET @ROW = -1;
SELECT ROUND(LAT_N,4)
FROM (
SELECT @ROW := @ROW +1 as rn
,LAT_N
FROM STATION
ORDER BY LAT_N
) A
WHERE RN IN (CEIL(@ROW/2), FLOOR(@ROW/2))