目录
题目
产品数据表: Products
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| new_price | int |
| change_date | date |
+---------------+---------+
(product_id, change_date) 是此表的主键(具有唯一值的列组合)。
这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。
编写一个解决方案,找出在 2019-08-16
时全部产品的价格,假设所有产品在修改前的价格都是 10
。
以 任意顺序返回结果表。
结果格式如下例所示。
示例 1:
输入:
Products 表:
+------------+-----------+-------------+
| product_id | new_price | change_date |
+------------+-----------+-------------+
| 1 | 20 | 2019-08-14 |
| 2 | 50 | 2019-08-14 |
| 1 | 30 | 2019-08-15 |
| 1 | 35 | 2019-08-16 |
| 2 | 65 | 2019-08-17 |
| 3 | 20 | 2019-08-18 |
+------------+-----------+-------------+
输出:
+------------+-------+
| product_id | price |
+------------+-------+
| 2 | 50 |
| 1 | 35 |
| 3 | 10 |
+------------+-------+
分析
编写一个解决方案,找出在 2019-08-16 时全部产品的价格。
关键点在找到 2019-08-16 前所有有改动的产品及其最新价格和没有修改过价格的产品
没有提供产品id列表,首先自行整理一份产品id列表,保证每个产品都考虑考虑到
(select distinct product_id from Products) a
需要找到2019-08-16 前所有有改动的产品
即针对一种产品,找到其在2019-08-16 前的最新价格,也就是最新日期的价格
select product_id,max(change_date) from Products
where change_date <= '2019-08-16'
group by product_id
将上述整理为新表b,左连接产品表a
left join (
select product_id,new_price from Products
where (product_id,change_date) in (
select product_id,max(change_date) from Products
where change_date <= '2019-08-16'
group by product_id
)
) b
on a.product_id = b.product_id
还存在没有修改过价格的产品,所有产品在修改前的价格都是 10 。
通过ifnull,若为null,则价格为10,ifnull(b.new_price,10)
代码
select a.product_id, ifnull(b.new_price,10) price
from (select distinct product_id from Products) a
left join (
select product_id,new_price from Products
where (product_id,change_date) in (
select product_id,max(change_date) from Products
where change_date <= '2019-08-16'
group by product_id
)
) b
on a.product_id = b.product_id
