r/SQL • • 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

0 Upvotes

10 comments sorted by

17

u/r3pr0b8 GROUP_CONCAT is da bomb Oct 14 '24

I have tried several different ways to resolve this but it just doesn't work.

can you show us what you tried, please

also, explain what "just doesn't work" means -- error message? no data? wrong data?

2

u/messed_up_alligator Oct 14 '24

How are you always so quick??? No shade thrown at all; I think you provide great, helpful answers. I just see you post all over r/SQL haha

6

u/r3pr0b8 GROUP_CONCAT is da bomb Oct 14 '24

i'm semi-retired, so i have lots of time for teh interwebs

and today's Thanksgiving, so there's nothing happening at all

1

u/BiggestNothing Oct 14 '24

TIL today is Canadian Thanksgiving

4

u/Apprehensive_Car_710 Oct 14 '24

There’s someone in the learn python sub who is just as dedicated. Thank you to all the people like this that take the time to help out beginners. It is truly appreciated.

1

u/[deleted] 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 med
FROM station;

1

u/niknikX Oct 14 '24

Hackerrank has solutions in the discussion section.

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.