产品数据表: 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
法一:UNION
思路:对于在2019-08-16当天及之前改变过价格的产品,只需要找到最后一次修改的价格即可;
对于在2019-08-16当天及之前没有改变过价格的产品,我们需要返回初始价格10;
分别计算出两种情况的结果,然后使用UNION合并。
select *
from
(select product_id,new_price as 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)
union
select distinct product_id,10 as price
from products
where product_id not in (select product_id from products where change_date<='2019-08-16') ) t
法二:
思路:可以先找到所有的产品,再找到所有 2019-08-16 前有修改的产品和他们最新的价格,使用 left join 将两个查询联合。如果产品没有价格,说明没有修改过,设置为 10,如果有价格,设置为最新的价格。
select p1.product_id,ifnull(p2.new_price,10) as price
from
(select distinct product_id from products) p1
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)
) p2
on p1.product_id = p2.product_id

本文介绍如何使用SQL查询在2019年8月16日当天和之前的Productstable,包括考虑未修改价格的产品。通过UNION或LEFT JOIN操作,找出每个产品在指定日期的最新价格或初始价格10。

861

被折叠的 条评论
为什么被折叠?



