LeetCode:197. Rising Temperature

题目描述

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 |
+----+

考查date_sub的用法,date_sub(date, interval k day)为找到date的前k天并返回。

date可用curdate()表示今天。

代码实现

1
2
select s.id from weather as s, weather as t
where s.temperature > t.temperature and t.recorddate = date_sub(s.recorddate, interval 1 day);