【SQL】温度比较

目录

题目

分析

代码


题目

表: Weather

复制代码
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id 是该表具有唯一值的列。
没有具有相同 recordDate 的不同行。
该表包含特定日期的温度信息

编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 id

返回结果无顺序要求 。

示例 1:

复制代码
输入:
Weather 表:
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+
输出:
+----+
| id |
+----+
| 2  |
| 4  |
+----+
解释:
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

分析

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

比较,使用交叉连接corss join

简洁写法 from Weather w1 , Weather w2

目标id, select w1.id

日期比较,前一日,datediff(w1.recordDate,w2.recordDate) = 1

温度比较,w1.temperature > w2.temperature

同时满足,and

代码

复制代码
select w1.id from Weather w1 , Weather w2
where datediff(w1.recordDate,w2.recordDate) = 1 and w1.temperature > w2.temperature

思考代码

复制代码
select a.ID, a.date
from weather as a cross join weather as b 
     on timestampdiff(day, a.date, b.date) = -1
where a.temp > b.temp;
相关推荐
A XMan.1 天前
域名Whois信息查询V2版API接入指南
数据库
heimeiyingwang1 天前
【架构实战】可观测性体系:从监控到全链路追踪
网络·数据库·架构
网管NO.11 天前
SQL 日期函数全套精讲!时间格式化、日期加减、年月日提取,做日报周报直接套用
数据库·sql
杨云龙UP1 天前
Linux 根分区被日志吃满?一次 58G Broker 日志清理实战_2026-05-20
linux·运维·服务器·数据库·hdfs·apache
sdk大全1 天前
Studio 3T for MongoDB 2025.13.0
数据库·mongodb
码农阿豪1 天前
平替MongoDB:金仓多模数据库助力电子证照国产化实践
数据库·mongodb
罗超驿1 天前
22.深入剖析JDBC架构:从原生API到企业级数据交互核心
java·数据库·mysql·面试
易辰君1 天前
【数据库】MongoDB深度解析与Python操作指南:从安装到实战操作全覆盖
数据库·mongodb
一直有一个ac的梦想1 天前
cmu15445 2025fall lec 18 transactions with two-phase lock
java·开发语言·数据库
身如柳絮随风扬1 天前
Redis 集群脑裂深度剖析:成因、危害与防丢失策略
数据库