上升的温度

发布时间 2023-08-08 17:57:43作者: 网抑云黑胶SVIP用户
表: Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
在 SQL 中,id 是该表的主键。
该表包含特定日期的温度信息
 

找出与之前(昨天的)日期相比温度更高的所有日期的 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)
1.首先要找到两个差异的时间,使用函数DATE_ADD()或者datediff()
2.通过自连接的差异1天进行分组
3.找到满足温度大于前一天的数据
SELECT t1.id
FROM Weather t1
JOIN Weather t2 ON t1.recordDate  = DATE_ADD( t2.recordDate,INTERVAL 1 day)
WHERE t1.temperature > t2.temperature;

select w1.id from Weather w1
join Weather w2 on datediff(w1.recordDate , w2.recordDate) = 1
where w1.temperature > w2.temperature