十分位数分析-客户和收入,反之亦然

时间:2018-08-09 05:50:02

标签: sql sql-server percentile

我正在尝试进行分析,以显示两件事。

  1. 十分之一(或百分位数)的客户及其收入,因此我可以看到10%的客户数量产生的收入最高。

  2. 收入的十分位数:有多少客户产生了10%的收入。

select yeardate, decile, sum(revenue) as revenue,  count(distinct(customername)) as cust_count
 from 
(
select yeardate,
customername,
ntile(10) over (order by sum(revenue) ) as decile,
sum(revenue) as revenue
from 
(select 
year(DateStamp) as yeardate ,
customername, 
sum(Sell) as revenue
from MarginListView
where reporttype = 'Invoice' and sell >0 and year(datestamp) = 2018
group by year(DateStamp), customername) d
group by yeardate, CustomerName) c
group by yeardate, decile
order by 1,2

我可以得到客户数量的十进制,但是收入却没有。

使用MS SQL服务器-感激任何帮助。

2 个答案:

答案 0 :(得分:0)

要获取产生收入10%的客户数量,请从累计收入开始:

select customername, sum(sell) as revenue,
       sum(sum(sell)) over (order by sum(sell) desc) as running_revenue
from MarginListView
where reporttype = 'Invoice' and sell > 0 and 
      year(datestamp) = 2018
group by customername;

要获取占10%的数字:

select count(*)
from (select customername, sum(sell) as revenue,
             sum(sum(sell)) over (order by sum(sell) desc) as running_revenue,
             sum(sum(sell)) over () as total_revenue
      from MarginListView
      where reporttype = 'Invoice' and sell > 0 and 
            year(datestamp) = 2018
      group by customername
     ) c
where running_revenue - revenue >= 0.1 * total_revenue;

答案 1 :(得分:0)

戈登-谢谢您的帮助。...确实的确使我朝着需要的方向前进。

我到此结束...

select 
yeardate, customername, 
sell,
cast((round(sum(sum(revenue_sub_tot)) over (order by sum(revenue_sub_tot) asc),2,2)) as decimal (2,2)) as revenue_percentiles,
cast((round(sum(sum(revenue_sub_tot)) over (order by sum(revenue_sub_tot) asc),1,1)) as decimal (2,2)) as revenue_deciles
from (select year(datestamp) as yeardate,
             customername, 
			 sum(sell) as sell,
			 sum(sell)/sum(sum(sell)) over () as revenue_sub_tot
      from MarginListView
      where reporttype = 'Invoice' and sell > 0 
      group by year(datestamp), customername
     ) c
	 group by yeardate, customername, sell
order by 1,3