79628865

Date: 2025-05-19 13:48:53
Score: 1
Natty:
Report link

Hope you will find this useful----
-----Median in SQL------

1st- Know the Median terminology for odd no.(2n+1) and even no.(2n)

Now I will show two scenarios of above with examples

suppose you have two data set with Table_1 with odd(499) and Table_2 with even(500).

Now querying for median of column_1(Table_1) and for median of column_1(Table_2)

--- Table_1 with odd(499) ------- :
SELECT

TOP 1 CAST(Column_1) AS Odd_Median

FROM

( SELECT TOP 250 Column_1 FROM Table_1 ORDER BY Column_1 DESC ) as T

ORDER BY Column_1 ASC;

--- Table_2 with even(500) ------- :

SELECT

(a+b)/2 AS Even_Median

FROM
(

SELECT

TOP 1 CAST(Column_1) AS a

FROM

( SELECT TOP 250 Column_1 FROM Table_1 ORDER BY Column_1 DESC ) UT

ORDER BY Column_1 ASC ) AS T

)
UNION

(
(SELECT TOP 1 CAST(Column_1) AS b

FROM

( SELECT TOP 251 Column_1 FROM Table_1ORDER BY Column_1 DESC ) as T

ORDER BY Column_1 ASC
)

;

Reasons:
  • Long answer (-0.5):
  • No code block (0.5):
  • Low reputation (1):
Posted by: Arnab Chhetri