DEV Community

Cover image for Hacker-rank SQL Median calculation
Pranava S Balugari
Pranava S Balugari

Posted on

Hacker-rank SQL Median calculation

It was really interesting to calculate Median of entries in the SQL database.

What is Median ?

Refer the link about [Median|https://en.wikipedia.org/wiki/Median]

Hackerrank SQL problem

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.

SET @index := -1;

SELECT
   ROUND(AVG(s.LAT_N), 4)
FROM
   (SELECT @index:=@index + 1 AS index, LAT_N
    FROM STATION
    ORDER BY LAT_N) AS s
WHERE
s.index IN (FLOOR(@index / 2) , CEIL(@index / 2));

Enter fullscreen mode Exit fullscreen mode

Top comments (0)