【高频SQL题目】再做一遍 1164.指定日期的产品价格

题目要求:

产品数据表: 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    |
+------------+-------+

解题思路:

限时返场,再做一遍。仍然遇到了好几个问题。

先观察:

product_id为1,在 2019-08-16刚好有数据

product_id 为2,在 2019-08-16没有数据,但是在2019-08-14 和2019-08-17号有数据。很显然要取2019-08-14这一天的价格

product_id为3,在 2019-08-16没有数据,在它之前也没有数据。所以就得用10.(题目里这样要求的)

1、要找各自的最靠近那个日期的去比较。

怎么找,是这个sql 的最重要的部分

用row_number (),根据产品id分组,框选日期要小于等于那一天,同时根据change_date倒序排序,取第一个

这样就可以找到最靠近目标日期的最新日期的数据

2、 日期应该大于等于 那天,还是小于等于那天?

同上。

3、日期范围这块我不熟悉!那天没有数据的时候。

那天没有数据没关系,用ifnull(),没有数据就给10.(题目里这样要求的)

-- 错误的sql。(因为row_number没用对。没有用分组)

-- select distinct p1.product_id,ifnull(p2.new_price,10) as price from Products p1 left join

-- ( select t.product_id,t.new_price from (select product_id,new_price ,row_number()over (order by change_date desc ) as rn from Products

-- where change_date<= '2019-08-16' ) t where t.rn =1 ) p2 on p1.product_id = p2.product_id

-- 正确的sql

select distinct p1.product_id,ifnull(p2.new_price,10) as price from Products p1 left join

( select t.product_id,t.new_price from (select product_id,new_price ,row_number()over (PARTITION BY product_id order by change_date desc ) as rn from Products

where change_date<= '2019-08-16' ) t where t.rn =1 ) p2 on p1.product_id = p2.product_id

相关推荐
SelectDB17 小时前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶18 小时前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构
掉头发的王富贵21 小时前
【StarRocks】极限十分钟入门StarRocks
数据库·sql·mysql
Nturmoils1 天前
WHERE 条件别凭习惯写,常用查询先跑一遍
数据库
Databend2 天前
在 AWS 中国峰会逛了一天,我在 Databend 展台看到了 Agent 数据基础设施的新思路
数据库·人工智能·agent
ClouGence3 天前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
飞将3 天前
从零实现数据库(2)——HashIndex + IndexManager
数据库
Nturmoils4 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波4 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_5 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库