##还有一个类型的题型,它是所有人的噩梦,那就是题都看不懂的题,这题真第一眼完全不知道它在说什么
1164. 指定日期的产品价格
产品数据表: Products
±--------------±--------+
| Column Name | Type |
±--------------±--------+
| product_id | int |
| new_price | int |
| change_date | date |
±--------------±--------+
这张表的主键是 (product_id, change_date)。
这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。
写一段 SQL来查找在 2019-08-16 时全部产品的价格,假设所有产品在修改前的价格都是 10。
查询结果格式如下例所示:
Products table:
±-----------±----------±------------+
| 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 |
±-----------±----------±------------+
Result table:
±-----------±------+
| product_id | price |
±-----------±------+
| 2 | 50 |
| 1 | 35 |
| 3 | 10 |
±-----------±------+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/product-price-at-a-given-date
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# Write your MySQL query statement below
select b.product_id,ifnull(a.new_price,10) price
from
(select distinct(product_id) from Products) b
left join
(select *
from Products c
where (c.product_id,c.change_date) in
(select p.product_id,Max(p.change_date) change_date
from Products p
where p.change_date<='2019-08-16'
group by p.product_id)
) a
on b.product_id =a.product_id