Function to Calculate Median in SQL Server

前端 未结 30 3152
孤独总比滥情好
孤独总比滥情好 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条回答
  •  不要未来只要你来
    2020-11-22 04:31

    This is as simple an answer as I could come up with. Worked well with my data. If you want to exclude certain values just add a where clause to the inner select.

    SELECT TOP 1 
        ValueField AS MedianValue
    FROM
        (SELECT TOP(SELECT COUNT(1)/2 FROM tTABLE)
            ValueField
        FROM 
            tTABLE
        ORDER BY 
            ValueField) A
    ORDER BY
        ValueField DESC
    

提交回复
热议问题