Percentile aggregate for SQL Server 2008 R2

后端 未结 1 1763
迷失自我
迷失自我 2021-01-07 15:20

I\'m using SQL Server 2008 R2. I need to compute a percentile value per group, something like:

SELECT id,
       PCTL(0.9, x) -- for the 90th percentile
FROM         


        
相关标签:
1条回答
  • 2021-01-07 16:13

    I like to do these calculations directly, using row_number()/rank() and window functions. The built-in functions are useful, but they don't actually save that much effort:

    SELECT id,
           MIN(CASE WHEN seqnum >= 0.9 * cnt THEN x END) as percentile_90
    FROM (select t.*,
                 row_number() over (partition by id order by x) as seqnum,
                 count(*) over (partition by id) as cnt
          from my_table t
         ) t
    GROUP BY id
    ORDER BY id;
    

    This takes the first value that is at the 90th percentile or greater. There are variations on this that can do the continuous version (take the largest value less than or equal to and the smallest one bigger than and interpolate).

    0 讨论(0)
提交回复
热议问题