[SQL] Weather Observation Station 20

μˆœλ™Β·2022λ…„ 5μ›” 13일
0

βœ… Weather Observation Station 20


πŸ“ 문제

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.
Input Format

The STATION table is described as follows:


πŸ’» 풀이

❗ 주의
μ•„λž˜ μ½”λ“œλŠ” ν™€μˆ˜μΈ κ²½μš°μ—λ§Œ 였λ₯˜ 없이 좜λ ₯됨

SELECT ROUND(AVG(LAT_N), 4)
FROM
(SELECT LAT_N,
 PERCENT_RANK() OVER(ORDER BY LAT_N) AS result FROM STATION) AS sub
WHERE result = 0.5;

πŸ’» μ •λ‹΅

SET @indexnum = -1;

SELECT ROUND(AVG(LAT_N), 4) AS Median
FROM(
    SELECT
        @indexnum := @indexnum + 1 AS row_num,
        LAT_N
    FROM STATION
    ORDER BY LAT_N ASC) AS sub
WHERE row_num IN (FLOOR(@indexnum / 2), CEIL(@indexnum / 2));

πŸ“Œ 정리

RANK() OVER(ORDER BY weight) AS result

ex) 90, 90, 85일 경우 1λ“±, 1λ“±, 3λ“±μœΌλ‘œ λ‚˜νƒ€λ‚¨ (곡동 λ“±μˆ˜λ§ŒνΌ κ±΄λ„ˆ λœ€)

DENSE_RANK() OVER(ORDER BY weight) AS result

ex) 90, 90, 85일 경우 1λ“±, 1λ“±, 2λ“±μœΌλ‘œ λ‚˜νƒ€λ‚¨

0개의 λŒ“κΈ€