【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
相关推荐
Lucifer三思而后行1 小时前
使用 BR 备份 TiDB 到 AWS S3 存储
数据库·tidb·aws
百***17072 小时前
Oracle分页sql
数据库·sql·oracle
qq_436962182 小时前
数据中台:打破企业数据孤岛,实现全域资产化的关键一步
数据库·人工智能·信息可视化·数据挖掘·数据分析
weixin_537765803 小时前
【数据库管理】MySQL主从复制详解
数据库·mysql
q***33373 小时前
数据库高安全—openGauss安全整体架构&安全认证
数据库·安全·架构
范纹杉想快点毕业4 小时前
《嵌入式开发硬核指南:91问一次讲透底层到架构》
java·开发语言·数据库·单片机·嵌入式硬件·mongodb
倚肆4 小时前
MySQL 配置文件属性详解
数据库·mysql
user_admin_god6 小时前
企业级管理系统的站内信怎么轻量级优雅实现
java·大数据·数据库·spring boot
百***22126 小时前
mysql的分区表
数据库·mysql
星光一影6 小时前
废品回收系统小程序源码
mysql·php·html5