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
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).