Function to Calculate Median in SQL Server

前端 未结 30 3365
孤独总比滥情好
孤独总比滥情好 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
    2020-11-22 04:43

    Justin's example above is very good. But that Primary key need should be stated very clearly. I have seen that code in the wild without the key and the results are bad.

    The complaint I get about the Percentile_Cont is that it wont give you an actual value from the dataset. To get to a "median" that is an actual value from the dataset use Percentile_Disc.

    SELECT SalesOrderID, OrderQty,
        PERCENTILE_DISC(0.5) 
            WITHIN GROUP (ORDER BY OrderQty)
            OVER (PARTITION BY SalesOrderID) AS MedianCont
    FROM Sales.SalesOrderDetail
    WHERE SalesOrderID IN (43670, 43669, 43667, 43663)
    ORDER BY SalesOrderID DESC
    

提交回复
热议问题