【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;
相关推荐
清水白石0082 分钟前
《Python 架构师的自动化哲学:从基础语法到企业级作业调度系统与 Airflow 止损实战》
数据库·python·自动化
阿华田5126 分钟前
MySQL性能优化大全
数据库·mysql·性能优化
kaico201813 分钟前
python操作数据库
开发语言·数据库·python
被摘下的星星14 分钟前
MySQL 别名使用规则详解
数据库·mysql
墨着染霜华20 分钟前
MySQL 重复数据删除语句
数据库·mysql
ego.iblacat22 分钟前
PostgreSQL 数据库
数据库·postgresql
wgzrmlrm741 小时前
如何解决ORA-28040没有匹配的验证协议_sqlnet.ora版本兼容设置
jvm·数据库·python
一江寒逸1 小时前
零基础从入门到精通MySQL(附加篇):面试八股文全集
数据库·mysql·面试
数厘1 小时前
2.6MySQL库表操作指南(电商数据分析专用)
数据库·mysql·数据分析
需要点灵感1 小时前
SQL Server 存储过程语法整理
数据库·sql