【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
相关推荐
treacle田18 分钟前
达梦数据库-达梦数据库中link链接访问远程Sql Sever-记录总结
数据库·达梦-sqlserver
ClouGence19 分钟前
不用搭复杂系统,也能做跨地域数据迁移?
大数据·数据库·saas
xcjbqd022 分钟前
SQL中视图能否嵌套存储过程_实现复杂自动化报表逻辑
jvm·数据库·python
听*雨声34 分钟前
软件设计师上午题5:数据库
数据库
hong781744 分钟前
阿里coding plan qwen3.6-plus 不支持图片上下文长度只有200K,问题出在哪?
linux·运维·数据库
Paxon Zhang1 小时前
MySQL 大师之路**数据库约束,表设计,CRUD**
android·数据库·mysql
HealthScience1 小时前
clinvar数据集说明
数据库·oracle
王的宝库1 小时前
【MySQL】主从复制原理详解:从 Binlog 到数据一致性
数据库·mysql
Vect__1 小时前
MySQL基本认知、库和表的操作
数据库·mysql
cyber_两只龙宝2 小时前
【Oracle】Oracle之DQL中SELECT的基础使用
linux·运维·服务器·数据库·云原生·oracle