Created
June 17, 2015 05:00
-
-
Save chrisknoll/1b38761ce8c5016ec5b2 to your computer and use it in GitHub Desktop.
Large scale percentile calculation in SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This query returns avg, stdev, max, min, p10, p25, p50 (median), p75, p90 values from the set of values defined from the rawData CTE.