题目来源:
leetcode题目,网址:1251. 平均售价 - 力扣(LeetCode)
解题思路:
首先根据产品 id 和 销售日期连接两表,然后根据产品 id 分组聚合,最后计算结果。
解题代码:
# Write your MySQL query statement below
select distinct a.product_id,round(sum(a.units*b.price)/sum(a.units),2) as average_price
from UnitsSold as a left join prices as b on a.product_id=b.product_id and a.purchase_date between b.start_date and b.end_date
group by a.product_id
总结:
与官方题解的思路差不多,区别是他使用了两次select。