简体   繁体   English

基于总计的 SQL 存储桶

[英]SQL bucket based on totals

I have a list of retailers and their total sales.我有一份零售商及其总销售额的清单。 I want to bucket them in 4 categories based on their total sales.我想根据他们的总销售额将他们分为 4 个类别。 I want to show 10% of retailers cover 70% of sales.我想显示 10% 的零售商覆盖了 70% 的销售额。

In the example below, I am trying to divide the retailers in 4 quantiles.在下面的示例中,我试图将零售商分成 4 个分位数。 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.在下面的案例中,所有 10 家零售商的总销售额为 4500。为了将这些零售商分成 4 个分位数,我按销售额从高到低对数据进行了排序,并为它们分配了分位数。

Sum of sales for retailers in each quantile is around 4500/4= 1100.每个分位数中零售商的销售额总和约为 4500/4=1100。

How can I replicate this logic in sql?如何在 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM