728x90
반응형
문제
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 decimal places.
Input Format
The STATION table is described as follows:

where LAT_N is the northern latitude and LONG_W is the western longitude.
풀이
위 station 테이블에서 lat_n 컬럼의 중간값 median을 구하는 문제이다. 중간값은 평균과 다른 의미이므로 여기서 AVG를 쓰면 안된다. LAT_N값을 일렬로 쭉 크기순으로 나열하고, 가운데 값을 구하면 된다. 만약 테이블의 row 갯수가 짝수라면, 가운데 두 값의 평균을 내야 한다. 다행히 select count(*) from station 을 해보니 499로, 중간값 구하는 게 조금 더 쉬워졌다.
rank()를 쓸 경우 값이 동일하면 스킵하기도 해서, 나는 row_number()를 선택했다. ceiling() 함수는 499/2 보다 크거나 같은 첫 정수값을 가져온다.
/*
Enter your query here.
Query the median of the Northern Latitudes (LAT_N) from STATION and round your answer to 4 decimal places.
*/
select round(t.lat_n, 4)
from
(
select id, lat_n, row_number() over(order by lat_n desc) as row_num
from station
) t
where t.row_num = ceiling((select count(*) from station)/2)
반응형
'Data > HackerRank' 카테고리의 다른 글
HackerRank - Occupations (0) | 2022.03.03 |
---|---|
HackerRank - Challenges (0) | 2022.03.02 |
HackerRank - Binary Tree Nodes (0) | 2022.03.02 |
HackerRank - The PADS (0) | 2022.03.01 |
HackerRank - Ollivander's (0) | 2022.03.01 |