197. 上升的温度 - 力扣(LeetCode)

Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id 是这个表的主键
该表包含特定日期的温度信息

编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id

返回结果 不要求顺序

查询结果格式如下例:

Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+

Result table:
+----+
| id |
+----+
| 2  |
| 4  |
+----+
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

一解

使用内连接,使用 DATEDIFF 函数计算两个时间差,过滤匹配条件

SELECT 
    weather.id as 'Id'
FROM 
    weather
        JOIN 
    weather w ON weather.Temperature > w.Temperature 
        AND DATEDIFF(weather.recordDate, w.recordDate) = 1
1 个赞

老师,这个函数DATEDIFF,是 DATEDIFF(datepart,startdate,enddate),是后面日期减前面日期得出数值。
是这样才对吧:AND DATEDIFF(w.recordDate, weather.recordDate) = 1

DATEDIFF 是 startdate - enddate,你这样写,应该是 DATEDIFF(w.recordDate, weather.recordDate) = -1,可以参考下面执行结果:

mysql> SELECT DATEDIFF('2017-11-30','2017-11-29') AS COL1,
    -> DATEDIFF('2017-11-30','2017-12-15') AS col2;
+------+------+
| COL1 | col2 |
+------+------+
|    1 |  -15 |
+------+------+
1 row in set (0.00 sec)