SQL实现LeetCode(197.上升温度)

2022-07-22,,

[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.

+---------+------------+------------------+
| id(int) | date(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:

+----+
| id |
+----+
|  2 |
|  4 |
+----+

这道题给了我们一个weather表,让我们找出比前一天温度高的id,由于id的排列未必是按顺序的,所以我们要找前一天就得根据日期来找,我们可以使用mysql的函数datadiff来计算两个日期的差值,我们的限制条件是温度高且日期差1,参见代码如下: 

解法一:

select w1.id from weather w1, weather w2
where w1.temperature > w2.temperature and datediff(w1.date, w2.date) = 1;

下面这种解法我们使用了mysql的to_days函数,用来将日期换算成天数,其余跟上面相同:

解法二:

select w1.id from weather w1, weather w2
where w1.temperature > w2.temperature and to_days(w1.date) = to_days(w2.date) + 1;

我们也可以使用subdate函数,来实现日期减1,参见代码如下:

解法三:

select w1.id from weather w1, weather w2
where w1.temperature > w2.temperature and subdate(w1.date, 1) = w2.date;

最后来一种完全不一样的解法,使用了两个变量pre_t和pre_d分别表示上一个温度和上一个日期,然后当前温度要大于上一温度,且日期差为1,满足上述两条件的话选出来为id,否则为null,然后更新pre_t和pre_d为当前的值,最后选出的id不为空即可:

解法四:

select id from (
select case when temperature > @pre_t and datediff(date, @pre_d) = 1 then id else null end as id,
@pre_t := temperature, @pre_d := date 
from weather, (select @pre_t := null, @pre_d := null) as init order by date asc
) id where id is not null;

参考资料:

到此这篇关于sql实现leetcode(197.上升温度)的文章就介绍到这了,更多相关sql实现上升温度内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《SQL实现LeetCode(197.上升温度).doc》

下载本文的Word格式文档,以方便收藏与打印。