题目需求
从订单明细表(order_detail)和收藏信息表(favor_info)统计2021国庆期间,每个商品总收藏量和购买量。
期望结果如下(截取部分):
sku_id | sku_sum (购买量) | favor_cn (收藏量) |
---|---|---|
1 | 38 | 1 |
10 | 205 | 2 |
11 | 225 | 2 |
需要用到的表:
订单明细表: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 |
收藏信息表:favor_info
user_id(用户id) | sku_id(商品id) | create_date(收藏日期) |
---|---|---|
101 | 3 | 2021-09-23 |
101 | 12 | 2021-09-23 |
101 | 6 | 2021-09-25 |
思路一
实现一
select nvl(t1.sku_id, t2.sku_id) as sku_id,
nvl(t1.favor_cn_tmp, 0) as favor_cn,
nvl(t2.sku_sum_tmp, 0) as sku_sum
from (
-- 1) 国庆期间每个品类的商品的收藏量
select sku_id,
count(*) as favor_cn_tmp
from favor_info
where '2021-10-01' <= create_date
and create_date <= '2021-10-07'
group by sku_id
) t1
full outer join
(
-- 2) 国庆期间每个品类的商品的购买量
select sku_id,
sum(sku_num) as sku_sum_tmp
from order_detail
where '2021-10-01' <= create_date
and create_date <= '2021-10-07'
group by sku_id
) t2
on t1.sku_id = t2.sku_id;
题目来源
http://practice.atguigu.cn/#/question/36/desc?qType=SQL