Function to Calculate Median in SQL Server

前端 未结 30 2812
孤独总比滥情好
孤独总比滥情好 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:28

    In SQL Server 2012 you should use PERCENTILE_CONT:

    SELECT SalesOrderID, OrderQty,
        PERCENTILE_CONT(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
    

    See also : http://blog.sqlauthority.com/2011/11/20/sql-server-introduction-to-percentile_cont-analytic-functions-introduced-in-sql-server-2012/

提交回复
热议问题