统计每个商品的销量最高的日期
题目需求
从订单明细表(order_detail)中统计出每种商品销售件数最多的日期及当日销量,如果有同一商品多日销量并列的情况,取其中的最小日期。期望结果如下:
sku_id(商品id) | create_date(销量最高的日期) | sum_num(销量) |
---|---|---|
1 | 2021-10-02 | 9 |
2 | 2021-10-04 | 60 |
3 | 2021-10-05 | 9 |
4 | 2021-10-07 | 10 |
5 | 2021-10-03 | 47 |
6 | 2021-10-03 | 8 |
7 | 2021-10-05 | 58 |
8 | 2021-10-08 | 59 |
9 | 2021-10-01 | 45 |
10 | 2021-10-08 | 94 |
11 | 2021-10-08 | 95 |
12 | 2021-10-08 | 83 |
代码实现
select
sku_id,
create_date,
sum_num
from
(
select
sku_id,
create_date,
sum_num,
row_number() over (partition by sku_id order by sum_num desc,create_date asc) rn
from
(
select
sku_id,
create_date,
sum(sku_num) sum_num
from order_detail
group by sku_id, create_date
)t1
)t2
where rn=1;