跳到主要内容

1164.指定日期的产品价格

序号题目难度
1164题目链接中等

题目大意​

编写一个解决方案,找出在 2019-08-16。 以 任意顺序 返回结果表。

产品数据表: Products

Column NameType
product_idint
new_priceint
change_datedate

(product_id, change_date) 是此表的主键(具有唯一值的列组合)。 这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。 一开始,所有产品价格都为 10。

示例​

输入​

Products 表:

product_idnew_pricechange_date
1202019-08-14
2502019-08-14
1302019-08-15
1352019-08-16
2652019-08-17
3202019-08-18

输出​

product_idprice
250
135
310

参考答案​

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
;