I have a list of retailers and their total sales. I want to bucket them in 4 categories based on their total sales. I want to show 10% of retailers cover 70% of sales.
In the example below, I am trying to divide the retailers in 4 quantiles. In the below case total sales for all 10 retailers is 4500. In order to divide these retailers in 4 quantiles, I have sorted data by sales from high to low and assign them quantile.
Sum of sales for retailers in each quantile is around 4500/4= 1100.
How can I replicate this logic in sql?
Here's sample data :-
If I understand correctly, you can use cumulative sums and some arithmetic. I think this does what you want.
select t.*,
ceiling(running_total * 4.0 / total_total)
from (select t.*, sum(total) over (order by total desc) as running_total,
sum(total) over() as total_total
from t
) t
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.