原题链接:http://practice.atguigu.cn/#/question/25/desc?qType=SQL
题目需求
从订单详情表中(order_detail)和商品(sku_info)中查询各个品类销售数量前三的商品。如果该品类小于三个商品,则输出所有的商品销量。
期望结果如下:
sku_id(商品id) | category_id(品类id) |
---|---|
2 | 1 |
4 | 1 |
1 | 1 |
8 | 2 |
7 | 2 |
5 | 2 |
12 | 3 |
11 | 3 |
10 | 3 |
需要用到的表:
订单明细表:order_detail
order_detail_id(订单明细id) | order_id(订单id) | sku_id(商品id) | create_date(下单日期) | price(商品单价) | sku_num(商品件数) |
---|---|---|---|---|---|
1 | 1 | 1 | 2021-09-30 | 2000.00 | 2 |
2 | 1 | 3 | 2021-09-30 | 5000.00 | 5 |
22 | 10 | 4 | 2020-10-02 | 6000.00 | 1 |
23 | 10 | 5 | 2020-10-02 | 500.00 | 24 |
24 | 10 | 6 | 2020-10-02 | 2000.00 | 5 |
商品信息表:sku_info
sku_id(商品id) | name(商品名称) | category_id(分类id) | from_date(上架日期) | price(商品价格) |
---|---|---|---|---|
1 | xiaomi 10 | 1 | 2020-01-01 | 2000 |
6 | 洗碗机 | 2 | 2020-02-01 | 2000 |
9 | 自行车 | 3 | 2020-01-01 | 1000 |
解题思路
SELECT sku_id,
category_id
FROM
(
SELECT od.sku_id,
si.category_id,
SUM(od.sku_num) AS sku_num,
ROW_NUMBER() OVER (PARTITION BY si.category_id ORDER BY SUM(od.sku_num) DESC) AS rn
FROM order_detail od
JOIN sku_info si
ON od. sku_id = si.sku_id
GROUP BY od.sku_id,
si.category_id
) t1
WHERE rn <= 3