【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;
相关推荐
今年不养猪只除草1 小时前
windows版本的时序数据库TDengine安装以及可视化工具
数据库·时序数据库·tdengine
极限实验室4 小时前
Easysearch 磁盘水位线注意事项
数据库
月落星还在4 小时前
Redis 单线程架构:化繁为简的性能哲学
数据库·redis·架构
十五年专注C++开发4 小时前
SQLiteStudio:一款免费开源跨平台的SQLite管理工具
数据库·c++·qt·sqlite
haoqi好奇4 小时前
uniapp+node+mysql接入deepseek实现流式输出
android·mysql·uni-app
啥都想学的又啥都不会的研究生5 小时前
Redis设计与实现-服务器中的数据库
运维·服务器·数据库·redis·笔记·缓存·性能优化
m0_748229995 小时前
redis 使用
数据库·redis·缓存
Foolforuuu5 小时前
什么样的场景适用redis?redis缓存是什么?
数据库·redis·缓存
m0_748234085 小时前
redis 清理缓存
数据库·redis·缓存
智享AI5 小时前
阿里云工作空间与Ollama(一)
数据库·阿里云·云计算