力扣1251年

 正确写法:

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 表,这样能保证每个产品的价格信息都被考虑到,同时也能关联上销售记录。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值