正确写法:
select p.product_id,
ifnull(round(sum(units*price)/sum(units),2),0) average_price
from prices p
left join unitssold u
on u.product_id=p.product_id
and u.purchase_date between start_date and end_date
group by p.product_id;
错误写法:
select u.product_id,
ifnull(round(sum(units*price)/sum(units),2),0) average_price
from unitssold u
right join prices p
on u.product_id=p.product_id
and u.purchase_date between start_date and end_date
group by u.product_id;
注意:
①ifnull的运用,保证没有数据时输出为0
②这里采用的是 unitssold
表(用 u
表示)右连接 prices
表(用 p
表示)。右连接会保证 prices
表中的所有记录都被包含在结果集中,即便 unitssold
表中没有与之匹配的记录。不过在这个场景下,我们关注的是每个产品是否有销售记录(即 unitssold
表中的记录),更合理的做法是让 prices
表作为主表去左连接 unitssold
表,这样能保证每个产品的价格信息都被考虑到,同时也能关联上销售记录。