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;
database icon
Finally, a unified workspace for your SQL development
Get more done, together, with PopSQL and SQL Server