【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;
相关推荐
Yushan Bai2 小时前
ORACLE RAC环境REDO日志量突然增加的分析
数据库·oracle
躺着听Jay2 小时前
Oracle-相关笔记
数据库·笔记·oracle
瀚高PG实验室2 小时前
连接指定数据库时提示not currently accepting connections
运维·数据库
运维成长记3 小时前
mysql数据库-中间件MyCat
数据库·mysql·中间件
尘客.4 小时前
DataX从Mysql导数据到Hive分区表案例
数据库·hive·mysql
华纳云IDC服务商4 小时前
SQL Server权限设置的几种方法
mysql·sqlserver
TiDB 社区干货传送门4 小时前
从开发者角度看数据库架构进化史:JDBC - 中间件 - TiDB
数据库·oracle·中间件·tidb·数据库架构
虾球xz5 小时前
游戏引擎学习第280天:精简化的流式实体sim
数据库·c++·学习·游戏引擎
uwvwko5 小时前
BUUCTF——web刷题第一页题解
android·前端·数据库·php·web·ctf
今天我又学废了5 小时前
Spark,SparkSQL操作Mysql, 创建数据库和表
大数据·mysql·spark