18 Star 92 Fork 52

柯基与佩奇 / 数据库SQL实战

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
70.查找与之前(昨天的)日期相比温度更高的所有日期的 Id.md 1.79 KB
一键复制 编辑 原始数据 按行查看 历史

查找与之前(昨天的)日期相比温度更高的所有日期的 Id

题目描述

给定一个 Weather 表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。

Create table If Not Exists Weather (Id int, RecordDate date, Temperature int)
Truncate table Weather
insert into Weather (Id, RecordDate, Temperature) values ('1', '2015-01-01', '10')
insert into Weather (Id, RecordDate, Temperature) values ('2', '2015-01-02', '25')
insert into Weather (Id, RecordDate, Temperature) values ('3', '2015-01-03', '20')
insert into Weather (Id, RecordDate, Temperature) values ('4', '2015-01-04', '30')

+---------+------------------+------------------+ | Id(INT) | RecordDate(DATE) | Temperature(INT) | +---------+------------------+------------------+ | 1 | 2015-01-01 | 10 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 | | 4 | 2015-01-04 | 30 | +---------+------------------+------------------+

例如,根据上述给定的 Weather 表格,返回如下 Id: +----+ | Id | +----+ | 2 | | 4 | +----+

答案

SELECT w2.Id
FROM Weather w1, Weather w2
WHERE DATEDIFF(w2.RecordDate, w1.RecordDate) = 1
AND w1.Temperature < w2.Temperature

题解

使用 JOIN 和 DATEDIFF() 子句

MySQL 使用 DATEDIFF 来比较两个日期类型的值。

因此,我们可以通过将 weather 与自身相结合,并使用 DATEDIFF() 函数。

SQL
1
https://gitee.com/wp950820/database-sql-combat.git
git@gitee.com:wp950820/database-sql-combat.git
wp950820
database-sql-combat
数据库SQL实战
master

搜索帮助