表:Prices
±--------------±--------+
| Column Name | Type |
±--------------±--------+
| product_id | int |
| start_date | date |
| end_date | date |
| price | int |
±--------------±--------+
(product_id,start_date,end_date) 是 prices 表的主键(具有唯一值的列的组合)。
prices 表的每一行表示的是某个产品在一段时期内的价格。
每个产品的对应时间段是不会重叠的,这也意味着同一个产品的价格时段不会出现交叉。
表:UnitsSold
±--------------±--------+
| Column Name | Type |
±--------------±--------+
| product_id | int |
| purchase_date | date |
| units | int |
±--------------±--------+
该表可能包含重复数据。
该表的每一行表示的是每种产品的出售日期,单位和产品 id。
编写解决方案以查找每种产品的平均售价。average_price 应该 四舍五入到小数点后两位。如果产品没有任何售出,则假设其平均售价为 0。
返回结果表 无顺序要求 。
结果格式如下例所示。
示例 1:
输入:
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 |
±-----------±--------------±------+
输出:
±-----------±--------------+
| product_id | average_price |
±-----------±--------------+
| 1 | 6.96 |
| 2 | 16.96 |
±-----------±--------------+
解释:
平均售价 = 产品总价 / 销售的产品数量。
产品 1 的平均售价 = ((100 * 5)+(15 * 20) )/ 115 = 6.96
产品 2 的平均售价 = ((200 * 15)+(30 * 30) )/ 230 = 16.96
本题需要计算每个产品的平均售价,平均售价 = 销售总额 / 总数量,因此我们只需要计算除每个产品的销售总额和总数量即可。
总数量可以直接使用 UnitsSold 计算得出,使用 GROUP BY 和 SUM 函数即可:
SELECT product_id, SUM(units) FROM UnitsSold GROUP BY product_id
因为每个产品不同时期的售价不同,因此在计算销售总额之前要先分别计算每个价格的销售总额。每个价格的销售总额为 对应时间内的价格∗对应时间内的数量。因为价格和时间在 Prices 表中,数量在 UnitsSold 表中,这两个表通过 product_id 关联,那么我们就可以使用 LEFT JOIN 将两个表连接,通过 WHERE 查询对应时间内每个产品的价格和数量,并计算出对应的销售总额。
SELECT
Prices.product_id AS product_id,
Prices.price * UnitsSold.units AS sales,
UnitsSold.units AS units
FROM Prices
LEFT JOIN UnitsSold ON Prices.product_id = UnitsSold.product_id
AND (UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date)
计算出产品每个价格的销售总额后,同样的使用 SUM 函数计算出产品所有时间的销售总额,然后除以总数量并使用 ROUND 函数保留两位小数即可。
select product_id,ifnull(round(sum(sales)/sum(units),2),0) as average_price
from(
select Prices.product_id AS product_id,Prices.price * UnitsSold.units AS sales,UnitsSold.units AS units
from Prices
left join UnitsSold on Prices.product_id = UnitsSold.product_id and (UnitsSold.purchase_date between Prices.start_date and Prices.end_date)
)T
group by product_id