找出销售额连续3天超过30000的商品
题目需求
从订单详情表(order_detail)中找出销售额连续3天超过30000的商品
结果如下:
Sku_id(商品id) |
---|
1 |
10 |
… |
代码实现
- 求每个商品每天的销售总额
select sku_id,
create_date,
sum(price * sku_num) order_amount
from order_detail
group by sku_id, create_date
having order_amount >= 30000;
- 求销售额连续3天以上超过30000的商品
select distinct sku_id
from
(
select sku_id,
count(*) over (partition by sku_id, date_rk) cn
from (
select sku_id,
create_date,
date_sub(create_date, rank() over (partition by sku_id order by create_date)) date_rk
from (
select sku_id,
create_date,
sum(price * sku_num) order_amount
from order_detail
group by sku_id, create_date
having order_amount >= 30000
) t1
) t2
)t3
where cn >= 3;
select sku_id
from (
select sku_id,
create_date,
date_sub(create_date, row_number() over (partition by sku_id order by create_date)) diff
from (
select sku_id,
create_date,
sum(price * sku_num) order_amount
from order_detail od
group by sku_id, create_date
having sum(price * sku_num) >= 30000
) t1
) t2
group by sku_id, diff
having count(*) >= 3;