I need a query that adjoins a list of data (simply one field of float data from a table) ordered ascending with the same field ordered descending.
For context's sake, I'm practicing my (very) rudimentary and (very) rusty SQL (MySQL, specifically). The larger problem I'm working to solve is this HackerRank question, which is to compute the median of the LAT_N
field from the STATION
table.
My strategy is to return from a table with the data ordered ascending in the first column (up_LAT_N
) and the data ordered descending in the second column (down_LAT_N
) the average of the first row that satisfies the condition (cond
) that the datum in the ascending ordered field is greater than or equal to the datum in the descending ordered field. This average would be the median.
I've tried the following:
SELECT up.LAT_N AS up_LAT_N,
down.LAT_N AS down_LAT_N,
CASE
WHEN up.LAT_N >= down.LAT_N THEN 1 ELSE 0
END AS cond
FROM
(SELECT LAT_N FROM STATION ORDER BY LAT_N) up,
(SELECT LAT_N FROM STATION ORDER BY LAT_N DESC) down
...but I the ordering doesn't seem to be preserved. I'm thinking I could basically do a 'join' of these two columns, but I'm not sure how to introduce an index to each of these on which to join.
Thanks, in advance!
EDIT: Sorry for the confusion: I wasn't looking for the solution to broader question of calculating the median -- just a little nudge to help me implement my own attempt at solving this problem!