同期商品售卖分析表
题目需求
从订单明细表(order_detail)中。
求出同一个商品在2021年和2022年中同一个月的售卖情况对比。
结果如下(截取部分):
Sku_id(商品id) | Month(月份) | 2020_skusum(2020销售量) | 2021_skusum(2021销售量) |
---|---|---|---|
1 | 9 | 0 | 11 |
1 | 10 | 2 | 38 |
10 | 10 | 94 | 205 |
11 | 10 | 95 | 225 |
12 | 9 | 0 | 43 |
12 | 10 | 83 | 20556 |
2 | 10 | 26 | 6018 |
3 | 9 | 0 | 5 |
3 | 10 | 1 | 30 |
4 | 9 | 0 | 9 |
代码实现
select
if(t1.sku_id is null,t2.sku_id,t1.sku_id),
month(if(t1.ym is null,t2.ym,t1.ym)) ,
if(t1.sku_sum is null ,0 ,t1.sku_sum) 2020_skusum,
if(t2.sku_sum is null ,0 ,t2.sku_sum) 2020_skusum
from
(
select
sku_id,
concat(date_format(create_date,'yyyy-MM'),'-01') ym,
sum(sku_num) sku_sum
from
order_detail
where
year(create_date)=2020
group by
sku_id,date_format(create_date,'yyyy-MM')
)t1
full join
(
select
sku_id,
concat(date_format(create_date,'yyyy-MM'),'-01') ym,
sum(sku_num) sku_sum
from
order_detail
where
year(create_date)=2021
group by
sku_id,date_format(create_date,'yyyy-MM')
)t2
on
t1.sku_id=t2.sku_id and month(t1.ym) = month(t2.ym)
select sku_id,
month(create_date) month,
sum(if(year(create_date)='2020', sku_num, 0)) 2020_skusum,
sum(if(year(create_date)='2021', sku_num, 0)) 2021_skusum
from order_detail
group by sku_id, month(create_date);