给定一个 Weather 表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。
+————-+—————————+—————————+
| 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:
+——+
| Id |
+——+
| 2 |
| 4 |
+——解决思路。查询两次Weather 只要w1.日期 减去一 等于 昨天的日期w2. RecordDate 并且w1.温度> w2.温度就可以了。但是这种速度非常慢
我的SQL:
SELECTw2.IdFROMWeather w1,Weather w2WHEREw1.RecordDate = DATE_SUB(w2.RecordDate, INTERVAL 1 DAY)AND w2.Temperature > w1.Temperature
其他SQL:将日期转成天数进行操作,发现简单了许多
示例一:
select wt1.Id
from Weather wt1,Weather wt2
where wt1.Temperature > wt2.Temperature AND TO_DAYS(wt1.RecordDate)-TO_DAYS(wt2.RecordDate)=1;
示例二:
SELECT
weather.id AS 'Id'
FROM
weather
JOIN
weather w ON DATEDIFF(weather.RecordDate, w.RecordDate) = 1
AND weather.Temperature > w.Temperature;
