最近做了京东的24年春招题,题目如下:
题目分析
本题要求统计每个商品在2024年第二季度(4月1日~6月30日)的销售总额,并在每个商品类别内按销售总额降序排名,同时输出商品的供应商名称。
输出字段:
- product_id(商品ID)
- product_name(商品名称)
- q2_2024_sales_total(2024年第二季度销售总额,若无销售为0)
- category_rank(在本类别内按销售总额降序的排名,1为最高)
- supplier_name(供应商名称)
输出顺序:按商品ID升序排列。
涉及知识点:
- SQL 多表连接(LEFT JOIN)
- 条件连接与时间筛选
- 分组聚合(SUM、COALESCE)
- 窗口函数(ROW_NUMBER() OVER PARTITION BY ... ORDER BY ...)
- 字段别名与排序(ORDER BY)
解答步骤
1. 关联商品、订单和供应商信息
- 用
product_info
作为主表,LEFT JOINorder_info
,条件为商品ID相同且订单日期在2024年4月1日至6月30日之间。 - 再 LEFT JOIN
supplier_info
,关联商品ID,获取供应商名称。
from product_info p
left join order_info o on p.product_id = o.product_id and order_date between '2024-04-01' and '2024-06-30'
left join supplier_info s on p.product_id = s.product_id
2. 统计每个商品的2024年Q2销售总额
- 用
sum(coalesce(total_amount,0))
统计每个商品的销售总额,若无销售则为0。
sum(coalesce(total_amount,0)) as q2_2024_sales_total
3. 计算类别内的销售额排名
- 用窗口函数
row_number() over(partition by p.category order by sum(coalesce(total_amount,0)) desc)
,在每个类别内按销售总额降序排名。
row_number() over(partition by p.category order by sum(coalesce(total_amount,0)) desc ) as category_rank
4. 分组与输出
- 按商品ID分组,输出商品ID、商品名称、销售总额、类别排名、供应商名称。
- 最终按商品ID升序排序。
group by product_id
order by product_id
完整代码
select p.product_id, p.product_name,
sum(coalesce(total_amount,0)) as q2_2024_sales_total,
row_number() over(partition by p.category order by sum(coalesce(total_amount,0)) desc ) as category_rank,
s.supplier_name
from product_info p
left join order_info o on p.product_id = o.product_id and order_date between '2024-04-01' and '2024-06-30'
left join supplier_info s on p.product_id = s.product_id
group by product_id
order by product_id
近似题目练习推荐
- 知识点:条件函数、分组聚合
- 知识点:窗口函数、分组聚合
如需更多类似题目,可在牛客网SQL练习区进行练习。