본문 바로가기

카테고리 없음

[HackerRank]Weather Observation Station 20 - MySQL에서 중앙값 구하기2 : SET 활용, CEIL, FLOOR

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

 

직전 포스트에 이어서 중앙값 구하는 방법 

[풀이]

 

  1. SET @ROW = -1; → 사용자 변수 초기화. 행 번호 붙이기 위해 -1부터 시작함.
  2. 내부 서브쿼리에서 LAT_N을 오름차순 정렬하고, 각 행에 @ROW := @ROW + 1로 번호 붙임 (0부터 시작).
  3. 바깥 쿼리에서 rn이 FLOOR(@ROW/2) 또는 CEIL(@ROW/2)인 행만 가져옴.
  4. 결과적으로 중앙값 위치에 있는 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))