sql notes: leetcode#197 rising temperature

Problem


Given a Weather table, write a SQL query to find all dates’ Ids with higher temperature compared to its previous (yesterday’s) dates.

1
2
3
4
5
6
7
8
+---------+------------------+------------------+
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
+---------+------------------+------------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+---------+------------------+------------------+

For example, return the following Ids for the above Weather table:

1
2
3
4
5
6
+----+
| Id |
+----+
| 2 |
| 4 |
+----+

Analysis


Join two Weather tables to iterate all possible (today, yesterday) and filter with
today.Temperature > yesterday.Temperature.

Solution


1
2
SELECT t.Id FROM Weather AS t, Weather AS y
WHERE DATEDIFF(t.RecordDate, y.RecordDate) = 1 AND t.Temperature > y.Temperature;

197. Rising Temperature
(中文版) SQL 笔记: Leetcode#197 Rising Temperature