题73:
根据下面两个表编写SQL查询以查找每种产品的平均售价,其中average_price 应该四舍五入到小数点后两位。
其中:
- Prices表:(product_id,start_date,end_date) 是 Prices 表的主键;Prices 表的每一行表示的是某个产品在一段时期内的价格;每个产品的对应时间段是不会重叠的,这也意味着同一个产品的价格时段不会出现交叉。
- UnitsSold表:UnitsSold 表没有主键,它可能包含重复项;nitsSold 表的每一行表示的是每种产品的出售日期,单位和产品 id。
解题思路:
select
product_id,
round(sum(sales)/sum(units),2) as average_price--计算平均售价
from(
select
p.product_id as product_id,
p.price * u.units as sales,--查询售价
u.units as units--查询销售量
from Prices as p
join UnitsSold u on p.product_id = u.product_id--连接两表
where u.purchase_date between p.start_date and p.end_date--确定销售出的时间在什么时间段
) t
group by product_id;--根据id分组