Function to Calculate Median in SQL Server

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

    The following query returns the median from a list of values in one column. It cannot be used as or along with an aggregate function, but you can still use it as a sub-query with a WHERE clause in the inner select.

    SQL Server 2005+:

    SELECT TOP 1 value from
    (
        SELECT TOP 50 PERCENT value 
        FROM table_name 
        ORDER BY  value
    )for_median
    ORDER BY value DESC
    

提交回复
热议问题