Function to Calculate Median in SQL Server

前端 未结 30 2775
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:03

According to MSDN, Median is not available as an aggregate function in Transact-SQL. However, I would like to find out whether it is possible to create this functionality (u

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:40

    Building on Jeff Atwood's answer above here it is with GROUP BY and a correlated subquery to get the median for each group.

    SELECT TestID, 
    (
     (SELECT MAX(Score) FROM
       (SELECT TOP 50 PERCENT Score FROM Posts WHERE TestID = Posts_parent.TestID ORDER BY Score) AS BottomHalf)
     +
     (SELECT MIN(Score) FROM
       (SELECT TOP 50 PERCENT Score FROM Posts WHERE TestID = Posts_parent.TestID ORDER BY Score DESC) AS TopHalf)
    ) / 2 AS MedianScore,
    AVG(Score) AS AvgScore, MIN(Score) AS MinScore, MAX(Score) AS MaxScore
    FROM Posts_parent
    GROUP BY Posts_parent.TestID
    

提交回复
热议问题