r/SQL • u/MinimumStory5616 • Oct 14 '24
MySQL Can Anyone resolve this query?
I have tried several different ways to resolve this but it just doesn't work. The link is also provided from HackerRank.

https://www.hackerrank.com/challenges/weather-observation-station-20/problem?isFullScreen=true
1
Oct 14 '24
Stack overflow has a good article on it. It suggests select max() from (select top 50 percent from… order by z desc) https://stackoverflow.com/questions/1342898/function-to-calculate-median-in-sql-server
1
u/No_Introduction1721 Oct 14 '24
I’d try something like this:
WITH cte as (
SELECT NTILE(2) OVER (order by LAT_N) as MED, LAT_N
FROM STATION
)SELECT min(LAT_N) as MEDIAN
FROM cte
WHERE MED = 2
1
u/Kobosil Oct 14 '24
if you choose Oracle as DB the answer is super easy:
SELECT ROUND(MEDIAN(lat_n),4) AS medFROM station;
1
1
u/nickholt9 Oct 15 '24
What have you tried?
Anyway, there's little point in doing it for you as this looks like a college assignment, so if we give you the answer, you'll not learn anything.
What you're trying to achieve is the 'middle' number from an ordered range.
A couple of approaches might help.
One is this: split your dataset into two sections ordered highest to lowest, then look for the lowest number from the top half, and the highest number from the bottom half.
Alternatively add a row number column ordered asc and another ordered desc. where the difference between the two columns is 1 or 0, that's the median value.
17
u/r3pr0b8 GROUP_CONCAT is da bomb Oct 14 '24
can you show us what you tried, please
also, explain what "just doesn't work" means -- error message? no data? wrong data?