Function to Calculate Median in SQL Server

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

    I try with several alternatives, but due my data records has repeated values, the ROW_NUMBER versions seems are not a choice for me. So here the query I used (a version with NTILE):

    SELECT distinct
       CustomerId,
       (
           MAX(CASE WHEN Percent50_Asc=1 THEN TotalDue END) OVER (PARTITION BY CustomerId)  +
           MIN(CASE WHEN Percent50_desc=1 THEN TotalDue END) OVER (PARTITION BY CustomerId) 
       )/2 MEDIAN
    FROM
    (
       SELECT
          CustomerId,
          TotalDue,
         NTILE(2) OVER (
             PARTITION BY CustomerId
             ORDER BY TotalDue ASC) AS Percent50_Asc,
         NTILE(2) OVER (
             PARTITION BY CustomerId
             ORDER BY TotalDue DESC) AS Percent50_desc
       FROM Sales.SalesOrderHeader SOH
    ) x
    ORDER BY CustomerId;
    

提交回复
热议问题