【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 分钟前
【开题答辩实录分享】以《自然灾害隐患点管理信息系统》为例进行答辩实录分享
数据库·spring boot
迎風吹頭髮8 分钟前
Linux服务器编程实践58-getnameinfo函数:通过socket地址获取主机名与服务名
开发语言·数据库·php
christine-rr21 分钟前
linux常用命令——其他
linux·服务器·网络·数据库·redis·ubuntu
一只专注api接口开发的技术猿35 分钟前
容器化与调度:使用 Docker 与 K8s 管理分布式淘宝商品数据采集任务
开发语言·前端·数据库
tryxr42 分钟前
MySQL 之索引为什么选择B+树
数据库·mysql·b+树·索引
曦樂~1 小时前
【Qt】信号与槽(Signal and Slot)- 简易计算器
开发语言·数据库·qt
ZYMFZ2 小时前
python面向对象
前端·数据库·python
lansye3 小时前
MySQL K8S日志分析与数据还原
mysql·k8s
lang201509283 小时前
MySQL 8.0原子性DDL全面解析
数据库·mysql
viperrrrrrrrrr74 小时前
milvus向量数据库
数据库·大模型·llm·milvus