1164.(Medium)指定日期的产品价格
产品数据表: 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution
先找出每个产品2019-08-16之前的价格 b表
a left join b, group by a.id 取b的价格,ifnull补10
select product_id, ifnull(max(b.new_price),10) price
from Products a left join
(
select *, rank() over (partition by product_id order by change_date desc) rk
from Products
where change_date <= '2019-08-16'
) b using(product_id)
where rk=1 or rk is null
group by 1
Last updated
Was this helpful?