Function to Calculate Median in SQL Server

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

    Using a single statement - One way is to use ROW_NUMBER() and filter using sub-query. Here is to find the median salary:

    SELECT AVG(a.Salary) FROM                                                             
    (SELECT ROW_NUMBER() OVER(ORDER BY Salary) as row_no, Salary FROM Employee)a
    CROSS JOIN
    (SELECT (COUNT(*)+1)*0.5 AS row_half FROM Employee )t
    WHERE a.row_no IN (FLOOR(t.row_half),CEILING(t.row_half))
    

    I have seen similar solutions over the net using FLOOR and CEILING but tried to use a single statement.

提交回复
热议问题