How to Calculate Percentiles in SQL Server

Let's say you want to look at the percentiles for products. You can use SQL Server's percentile_cont()function to do that:

select
  percentile_cont(0.25) within group(order by price) over () as percentile_cont_25,
  percentile_cont(0.50) within group(order by price) over () as percentile_cont_50,
  percentile_cont(0.75) within group(order by price) over () as percentile_cont_75,
  percentile_cont(0.95) within group(order by price) over () as percentile_cont_95
from products;

If you want to view those percentiles by category:

select distinct category,
  percentile_cont(0.25) within group(order by price) over (partition by category) as percentile_cont_25,
  percentile_cont(0.50) within group(order by price) over (partition by category) as percentile_cont_50,
  percentile_cont(0.75) within group(order by price) over (partition by category) as percentile_cont_75,
  percentile_cont(0.95) within group(order by price) over (partition by category) as percentile_cont_95
from products
order by category;
Cta

Better SQL for the people

Get more done with PopSQL and SQL Server