# 包含的字段:商品 ID、商品名称、该商品在 2024 年第二季度的销售总额,该商品在所属类别的销售排名,所属供应商。查询出来的数据按照商品 ID 升序排列。要求查询出来的表格的字段如下:
# product_id: 商品的唯一标识符。
# product_name: 商品的名称。
# q2_2024_sales_total: 2024 年第二季度的销售总额。4、5、6月份属于第二季度
# category_rank: 在所属类别的销售排名。
# supplier_name: 所属供应商。
#难点在于要筛选第一季度的订单,如果先连接order_info和product_info,再用where 筛选就会把Product E漏掉,所以要先单独对order_info处理,先把第一季度的订单筛选出来,再和product_info连接

select p.product_id product_id
,product_name
,sum(if(total_amount is null,0,total_amount)) q2_2024_sales_total
,row_number() over(partition by category order by sum(total_amount) desc) category_rank
# 当查询包含GROUP BY时,PARTITION BY只能使用:
# GROUP BY中包含的列
# 聚合函数计算的结果
# 不能使用未包含在GROUP BY中的原始表列
,supplier_name
from product_info p  
left join (
    select *from
order_info  where substr(order_date,6,2) in ("04",'05','06')
# 时间要放在订单表中先执行。因为商品表中有一个不满足该条件但也不能筛去的商品E。
) o
on p.product_id=o.product_id
left join supplier_info s
on p.product_id=s.product_id
group by p.product_id,product_name,supplier_name,category
# 因为每个商品id对应的商品名称,供应商和类别都一样,所以在sum(销售额)时,不会受影响。
order by product_id ;