题解 | 分析每个商品在不同时间段的销售情况
分析每个商品在不同时间段的销售情况
https://www.nowcoder.com/practice/eec7a93e1ab24233bd244e04e910d2f9
关键(易错点):用where语句排除了第二季度无销售额的商品,故应该product表left join第二季度汇总表,才能确保所有商品都有记录。
总结:检查where筛选是否会排除某些需要的信息;表连接时要时刻关注是否出现null,是否需要处理
with sale_q2_table as (
select p.product_id
,round(if(sum(total_amount) is not null,sum(total_amount),0),2) q2_2024_sales_total
,product_name
,category
from product_info p
left join order_info o on p.product_id=o.product_id
where year(order_date) =2024 and month(order_date) in (4,5,6)
group by p.product_id,product_name,category
)
select p.product_id product_id
,p.product_name
,case when q2_2024_sales_total!='None' and q2_2024_sales_total is not null then q2_2024_sales_total else 0.00 end
q2_2024_sales_total
,rank()over(partition by p.category order by q2_2024_sales_total desc) category_rank
,supplier_name
from product_info p
left join sale_q2_table sa on p.product_id=sa.product_id
left join supplier_info s on p.product_id=s.product_id
order by product_id
