Function to Calculate Median in SQL Server

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

    Frequently, we may need to calculate Median not just for the whole table, but for aggregates with respect to some ID. In other words, calculate median for each ID in our table, where each ID has many records. (based on the solution edited by @gdoron: good performance and works in many SQL)

    SELECT our_id, AVG(1.0 * our_val) as Median
    FROM
    ( SELECT our_id, our_val, 
      COUNT(*) OVER (PARTITION BY our_id) AS cnt,
      ROW_NUMBER() OVER (PARTITION BY our_id ORDER BY our_val) AS rnk
      FROM our_table
    ) AS x
    WHERE rnk IN ((cnt + 1)/2, (cnt + 2)/2) GROUP BY our_id;
    

    Hope it helps.

提交回复
热议问题