给定一个 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 |
+----+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rising-temperature
题解:参考官方题解,了解到了 datediff(date1,date2) = m :date1 - date2 = m(相差m天)
select
b.id
from
Weather as a,
Weather as b
where
datediff(b.RecordDate,a.RecordDate)=1
and b.Temperature > a.Temperature;
内连接优化后:
select
b.id
from
Weather as a
join
Weather as b
on
datediff(b.RecordDate,a.RecordDate)=1
and b.Temperature > a.Temperature;