欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > 【SQL】指定日期的产品价格

【SQL】指定日期的产品价格

2024/10/24 5:21:20 来源:https://blog.csdn.net/weixin_73404807/article/details/141496875  浏览:    关键词:【SQL】指定日期的产品价格

目录

题目

分析

代码


题目

产品数据表: Products

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| new_price     | int     |
| change_date   | date    |
+---------------+---------+
(product_id, change_date) 是此表的主键(具有唯一值的列组合)。
这张表的每一行分别记录了 某产品 在某个日期 更改后 的新价格。

编写一个解决方案,找出在 2019-08-16 时全部产品的价格,假设所有产品在修改前的价格都是 10 。

以 任意顺序 返回结果表。

结果格式如下例所示。

示例 1:

输入:
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    |
+------------+-------+

分析

编写一个解决方案,找出在 2019-08-16 时全部产品的价格。

关键点在找到 2019-08-16 前所有有改动的产品及其最新价格和没有修改过价格的产品

没有提供产品id列表,首先自行整理一份产品id列表,保证每个产品都考虑考虑到

(select distinct product_id from Products) a

需要找到2019-08-16 前所有有改动的产品

即针对一种产品,找到其在2019-08-16 前的最新价格,也就是最新日期的价格

select product_id,max(change_date) from Products

where change_date <= '2019-08-16'

group by product_id

将上述整理为新表b,左连接产品表a

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

)

) b

on a.product_id = b.product_id

还存在没有修改过价格的产品,所有产品在修改前的价格都是 10 。

通过ifnull,若为null,则价格为10,ifnull(b.new_price,10)

代码

select a.product_id, ifnull(b.new_price,10) price
from (select distinct product_id from Products) a
left join (select product_id,new_price from Productswhere (product_id,change_date) in (select product_id,max(change_date) from Productswhere change_date <= '2019-08-16'group by product_id)
) b
on a.product_id = b.product_id

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com