题解 | 每个商品的销售总额
题目要求拆解:
- 需要 商品名称 ,销售总量,商品在类目下的排名
- 要统计商品维度的销售总量
- 排序:
- 销售总量降序
- 要展示排名:按照所属类别降序,排名相同按照product_id 升序
思路分析:
- 初步分析,我们需要的name,category,quantity 分别存于orders表和products表中,我们要数据是要可以被统计在各类目下的商品销售信息,所以数据范围应该得即满足orders表也满足于products表,所以使用inner join。
- 因为要输出排名信息,首先想到是要使用窗口函数;进一步分析,使用窗口函数排序数据要用到销售总量,所以使用子查询先将统计好的商品维度的销售总量准备好。
- 因为题目中要求“每个商品在其所属类别内的排名,排名相同的商品可以按照 product_id 升序排序” ,所以在rank的时候需要用到product_id,因此在子查询时也需要输出product_id字段。
- Order by category,total_sales desc
select
t.product_name,
t.total_sales,
rank()over(
partition by t.category
order by t.total_sales desc, t.product_id
) as category_rank
from
(
select
p.name as product_name,
sum(o.quantity) as total_sales,
p.category,
p.product_id
from
orders o
inner join products p on o.product_id = p.product_id
group by
p.name,
p.category,
p.product_id
) as t
order by t.category, t.total_sales desc


查看16道真题和解析