上升的温度
给定一个 Weather
表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。
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 | +---------+------------------+------------------+
|
例如,根据上述给定的 Weather
表格,返回如下 Id:
1 2 3 4 5 6
| +----+ | Id | +----+ | 2 | | 4 | +----+
|
解题思路
DATEDIFF
该函数求两个日期的天数差(执行时间太长)
TO_DAYS
代码
1 2 3 4 5
| SELECT w1.`Id` FROM weather w1,weather w2 WHERE DATEDIFF(w1.`RecordDate`,w2.`RecordDate`)=1 AND w1.`Temperature`>w2.`Temperature`
|
1 2 3 4 5
| SELECT w1.`Id` FROM weather w1,weather w2 WHERE TO_DAYS(w1.`RecordDate`)-TO_DAYS(w2.`RecordDate`)=1 AND w1.`Temperature`>w2.`Temperature`
|