【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 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
相关推荐
SelectDB14 分钟前
从 Machine-Readable 到 Agent-Ready:面向智能体的数据库接口演进
大数据·数据库·agent
画江湖Test21 分钟前
Redis 块的原理
数据库·redis·缓存·性能优化
流烟默23 分钟前
国产数据库CERDB是什么以及服务启停
数据库·cerdb
数据库小学妹43 分钟前
关系型数据库核心原理拆解:SQL解析、事务引擎、存储结构全链路分析
数据库·经验分享·sql·数据库架构·dba
海市公约1 小时前
Redis主从复制全量同步七步时序与命令传播机制详解
数据库·redis·缓存·主从复制·高可用架构·全量同步
我是唐青枫1 小时前
Java JdbcTemplate 实战指南:用 Spring 轻量完成数据库增删改查
java·数据库·spring
逍遥运德1 小时前
PostgreSQL ---【序列】用法详解
后端·sql·postgresql
梓䈑1 小时前
【MySQL】MySQL安装 和 配置
数据库·mysql
小马爱打代码1 小时前
Redis 和 MySQL 双写一致性:延迟双删、读写锁、MQ、Canal 怎么选?
数据库·redis·mysql