For even rows formula for median is (104.5 + 108)/2 for table below and For odd rows it is 108 for table below
Total Total
100 100
101 101
104.5 104.5
108 108
108.3 108.3
112 112
114
Code be开发者_Python百科low works in SQL Server 2008 but not in SQL Server 2000 as it does not understand row_number()
and over
.
How can we change the lower code to make it work on SQL Server 2000?
select avg(Total) median from
(select Total,
rnasc = row_number() over(order by Total),
rndesc = row_number() over(order by Total desc)
from [Table]
) b
where rnasc between rndesc - 1 and rndesc + 1
If you only want a median, you may use this simple query.
SELECT
(
(SELECT MAX(Total) FROM
(SELECT TOP 50 PERCENT Total FROM [Table] ORDER BY Total) AS BottomHalf)
+
(SELECT MIN(Total) FROM
(SELECT TOP 50 PERCENT Total FROM [Table] ORDER BY Total DESC) AS TopHalf)
) / 2.0 AS Median
Source: Function to Calculate Median in Sql Server
SELECT Median = AVG(Total) FROM
(
SELECT Total FROM (
SELECT TOP 1 Total = Total * 1.0 FROM
(
SELECT TOP 50 PERCENT Total
FROM dbo.[Table] ORDER BY Total
) AS sub_a
ORDER BY 1 DESC
) AS sub_1
UNION ALL
SELECT Total FROM (
SELECT TOP 1 Total = Total * 1.0 FROM
(
SELECT TOP 50 PERCENT Total
FROM dbo.[Table] ORDER BY Total DESC
) AS sub_b
ORDER BY 1
) AS sub_2
) AS median;
精彩评论