天天看点

超详细解析:统计某品类的店铺销售额占比前20%

假设现有三张表如下,使用SQL查询某品类销售额占比在前20%的店铺名称和排名。

category表

超详细解析:统计某品类的店铺销售额占比前20%

seller表

超详细解析:统计某品类的店铺销售额占比前20%

sales表

超详细解析:统计某品类的店铺销售额占比前20%

思路:

  1. 计算某品类的店铺销售额降序排名。
  2. 在1的基础上计算每个品类的店铺累积销售额占比。
select b.ProductName,b.price,b.sales,b.SellerNick,b.categoryName,b.销售额,row_number()over() 排名 
from 
(select a.*,cume_dist()over(order by a.销售额 desc) 'rank' 
from 
(SELECT sa.ProductName,sa.price,sa.sales,se.SellerNick,c.categoryName,price*sales 销售额 
FROM sales sa 
join 
(select distinct SellerKey,SellerNick from seller
) se 
on sa.SellerKey = se.SellerKey 
join category c on c.categoryKey = sa.categoryKey where c.categoryName='某品类' 
group by SellerNick order by 销售额 desc
) a
) b 
where b.rank < 0.2;