Prices table:
±-----------±-----------±-----------±-------+
| product_id | start_date | end_date | price |
±-----------±-----------±-----------±-------+
| 1 | 2019-02-17 | 2019-02-28 | 5 |
| 1 | 2019-03-01 | 2019-03-22 | 20 |
| 2 | 2019-02-01 | 2019-02-20 | 15 |
| 2 | 2019-02-21 | 2019-03-31 | 30 |
±-----------±-----------±-----------±-------+
UnitsSold table(可能存在重复数据):
±-----------±--------------±------+
| product_id | purchase_date | units |
±-----------±--------------±------+
| 1 | 2019-02-25 | 100 |
| 1 | 2019-03-01 | 15 |
| 2 | 2019-02-10 | 200 |
| 2 | 2019-03-22 | 30 |
±-----------±--------------±------+
已知销量表和单价表,计算所有产品的平均售价,四舍五入小数点两位
select p.product_id as product_id,
ifnull(round(sum(p.price*u.units) / sum(u.units),2),0) as average_price
from Prices p left join UnitsSold u
on (u.purchase_date between p.start_date and p.end_date)
and p.product_id = u.product_id
group by p.product_id