select 
product_id,
product_name,
q2_2024_sales_total,
rank() over(partition by category order by q2_2024_sales_total desc) category_rank,
supplier_name
from (
    select p.product_id product_id,
    max(product_name) product_name,
    sum(ifnull(total_amount,0)) q2_2024_sales_total,
    max(supplier_name) supplier_name,
    max(category) category
    from product_info p 
    left join order_info d on p.product_id=d.product_id and (order_date between '2024-04-01' and '2024-06-30')
    left join supplier_info s on p.product_id=s.product_id
   #left join supplier_info s on d.product_id=s.product_id
   # where order_date between '2024-04-01' and '2024-06-30'
    group by product_id
) t
order by product_id

1、注意如何保留空值为0:ifnull函数,如果为空就设为0

2、修改条件所在位置

  • WHERE 子句:过滤的是连接后的整个结果集,会把不满足条件的行(包括因右表无匹配导致 NULL 的行)全部过滤掉,无法保留无匹配的主表记录。
  • JOIN 条件:是在连接过程中进行匹配判断,若右表无符合条件的记录,主表(如果是 LEFT JOIN 场景下的左表)记录依然能保留,后续通过聚合函数等处理,就能展示出如 q2_2024_sales_total = 0 这类代表无销售的行。

3、修改联结条件,均以product_info表为基准,以确保E的数据始终存在而且不出现null

left join supplier_info s on p.product_id=s.product_id  -- 修改连接条件