Skip to content

Instantly share code, notes, and snippets.

@chrisknoll
Created June 17, 2015 05:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisknoll/1b38761ce8c5016ec5b2 to your computer and use it in GitHub Desktop.
Save chrisknoll/1b38761ce8c5016ec5b2 to your computer and use it in GitHub Desktop.
Large scale percentile calculation in SQL
with rawData(count_value) as -- replace below query to get the values you would like to find percentiles of
(
select p.YEAR_OF_BIRTH
from dbo.PERSON p
),
overallStats (avg_value, stdev_value, min_value, max_value, total) as
(
select avg(1.0 * count_value) as avg_value,
stdev(count_value) as stdev_value,
min(count_value) as min_value,
max(count_value) as max_value,
count(*) as total
from rawData
),
aggData (count_value, total, accumulated) as
(
select count_value,
count(*) as total,
SUM(count(*)) OVER (ORDER BY count_value ROWS UNBOUNDED PRECEDING) as accumulated
FROM rawData
group by count_value
)
select o.total as count_value,
o.min_value,
o.max_value,
o.avg_value,
o.stdev_value,
MIN(case when d.accumulated >= .50 * o.total then count_value else o.max_value end) as median_value,
MIN(case when d.accumulated >= .10 * o.total then count_value else o.max_value end) as p10_value,
MIN(case when d.accumulated >= .25 * o.total then count_value else o.max_value end) as p25_value,
MIN(case when d.accumulated >= .75 * o.total then count_value else o.max_value end) as p75_value,
MIN(case when d.accumulated >= .90 * o.total then count_value else o.max_value end) as p90_value
from aggData d
cross apply overallStats o
GROUP BY o.total, o.min_value, o.max_value, o.avg_value, o.stdev_value
;
@chrisknoll
Copy link
Author

This query returns avg, stdev, max, min, p10, p25, p50 (median), p75, p90 values from the set of values defined from the rawData CTE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment