top of page

Calculating the Median in SQL Server - Consider This Hacker Rank Problem

Feb 22

1 min read

0

12

0

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 decimal places.


Input Format


The STATION table is described as follows:



where LAT_N is the northern latitude and LONG_W is the western longitude.


The solution is simple when you use the inbuilt median function.


Consider the following code:


The CTE A is used to add a uniform column to the code so that it can be added to the PERCENTILE_DISC function as the partition argument so that the median is calculated over the entire dataset.

The actual select statement is just selecting the max(median), however, due to the uniform partition statement the result is the same on every line.

Then it is simply a case of casting the result to a decimal with 4 decimal places to arrive at the correct result.


Hope this was helpful!



Feb 22

1 min read

0

12

0

Comments

Share Your ThoughtsBe the first to write a comment.
bottom of page