SQL 스터디/HackerRank

[해커랭크] MySQL PERCENT_RANK - Weather Observation Station 20

황금붕어빵 2023. 9. 14. 06:28

 

 

 


 

 

Weather Observation Station 20 | HackerRank

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

www.hackerrank.com

LAT_N 값 중에서 중앙값(Median)을 찾는 문제입니다.

문제)
A median is defined as a number separating the higher half of a data set from the lower half. Query the median of the Northern Latitudes (LAT_N) from STATION and round your answer to 4 decimal places.

출처 : 해커랭크

이번 문제는 WINDOW 함수를 활용해서 풀어볼텐데요.

 

PERCENT_RANK 함수를 활용해서 lat_n 값 중에서 50%에 해당하는 값을 찾으면 될 것 같습니다.

 

select round(lat_n,4)
from station
where lat_n in (
		select lat_n
                from (
                      select lat_n
                           , percent_rank() over(order by lat_n) as percent
                      from station
                      ) calcum
                where percent = 0.5
                )

WHERE 절에 서브쿼리 형태로 하여 중간값에 있는 lat_n 값을 찾아주면 됩니다.

 

PERCENT_RANK 함수를 활용하고 어떠한 조건에 맞추어서 순위를 나눌 필요는 없기 때문에 PARTITION BY는 제외해주고 ORDER BY를 활용하여 lat_n 값의 PERCENT_RNAK 값을 만들어줍니다.

 

해당 쿼리를 감싸준 뒤에 50%(0.5)에 위치한 lat_n 값을 출력해줍니다.

 

마지막으로 해당 값을 소수점 4자리 이하로 반올림해야하기 때문에 round 함수를 사용하면 됩니다.

 

 

MySQL에서는 MAX와 MIN 같이 중앙값을 추출하는 함수는 없으며 위와 같은 방법으로 Median(중앙값)을 추출할 수 있습니다.