SQL (DB2) 查询以获取前 10% 的收入贡献客户的数量

SQL (DB2) query to get count of top 10% revenue contributing customers

我在一家电信公司工作,我需要 运行 为当月贡献公司总收入 10% 的最有价值客户制定一个计划。我想知道有多少客户符合资格参加此计划?我正在使用 SQL DB2。

Ex - 在下面 table 中,收入总和为 5000,其 10% 为 500,我想知道收入总和为 500 或略高于 500

Customers   Revenue
A   156
B   259
C   389
D   125
E   578
F   321

查找总收入至少占总收入 10% 的所有客户:

select customer
from the_table
group by customer
having sum(revenue) >= (select sum(revenue) * 0.1 from the_table);

您的示例数据没有显示这一点,但这也涉及 table 中每个客户的多行(您的示例每个客户只有一行)

得到的计数:

select count(*) 
from (
  select customer
  from the_table
  group by customer
  having sum(revenue) >= (select sum(revenue) * 0.1 from the_table)
) t

我将这个问题解释为想要总收入至少占总收入 10% 的最高收入客户。

您需要一个累计金额:

select count(*)
from (select t.*, sum(revenue) over (order by revenue desc) as cume_rev,
             sum(revenue) over () as tot_rev
      from t
     ) t
where cume_rev <= tot_rev * 0.1;

这假设每个客户一行。

编辑:

对于 "just above",where 子句应为:

    where cume_rev - revenue < tot_rev * 0.1;