LeetCode每天一题

197. 上升的温度

题目:

197. 上升的温度

难度简单132

SQL架构

给定一个 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 |
+----+

通过次数43,716

提交次数84,754

解题思路

首先我们先尝试一下如何查

这里的查询需要用到自身查询

这里发现提交会报错,思路确实这这样的,如果RecordDate不是Date型的确实可以这样使用。但是如果是Date我们就不能这样进行比较。

1
2
3
select w2.id
from Weather w1,Weather w2
where w2.RecordDate=w1.RecordDate+1 and w1.Temperature<w2.Temperature;

这里要使用关于Date的一些函数

DATEDIFF() 函数返回两个日期之间的时间。
语法
1
DATEDIFF(datepart,startdate,enddate)

startdateenddate 参数是合法的日期表达式。

既然要用到函数,那么where就不能用了,就要用连接查询了。

1
2
3
4
5
select 
w1.id 'Id'
from
Weather w1 join Weather w2
on Datediff(w1.RecordDate,w2.RecordDate) = 1 and w1.Temperature > w2.Temperature;

答案解析

1
2
3
4
5
6
# Write your MySQL query statement below
select
w1.id 'Id'
from
Weather w1 join Weather w2
on Datediff(w1.RecordDate,w2.RecordDate) = 1 and w1.Temperature > w2.Temperature;
点击查看
-------------------本文结束 感谢您的阅读-------------------