1164.指定日期的产品价格
| 序号 | 题目 | 难度 |
|---|---|---|
| 1164 | 题目链接 | 中等 |
题目大意
编写一个解决方案,找出在 2019-08-16。 以 任意顺序 返回结果表。
产品数据表: Products
| Column Name | Type |
|---|---|
| product_id | int |
| new_price | int |
| change_date | date |
(product_id, change_date) 是此表的主键(具有唯一值的列组合)。
这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。
一开始,所有产品价格都为 10。
示例
输入
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 |
参考答案
with t1 as (
select
product_id
,new_price price
,row_number() over(partition by product_id order by change_date desc) as rn
from Products
where change_date <= '2019-08-16'
)
select
t0.product_id
, IF(t1.price is null, 10, t1.price) as price
from (select product_id from Products group by 1) t0
left join t1
on t0.product_id = t1.product_id
and t1.rn = 1
;