【LeetCode 简单题】50-上升的温度

声明:

今天是第50道题。给定一个 Weather 表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

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

解法1。两表直接关联,用where筛选日期差1天,温度更高的样本Id,还有to_days()函数的用法,耗时540 ms, 在Rising Temperature的MySQL提交中击败了74.45% 的用户,代码如下。

  • to_days(date):给出一个日期date,返回一个天数(从公元0年的天数); 
select w1.Id from Weather w1, Weather w2 where to_days(w1.RecordDate) - to_days(w2.RecordDate) = 1 and w1.Temperature > w2.Temperature

解法2。两表直接关联,用where筛选日期差1天,温度更高的样本Id,还有datediff()函数的用法,耗时497 ms, 在Rising Temperature的MySQL提交中击败了84.89% 的用户,代码如下。

select w1.Id from Weather w1, Weather w2 where datediff(w1.RecordDate, w2.RecordDate) = 1 and w1.Temperature = w2.Temperature

解法3。两表直接关联,用where筛选日期差1天,温度更高的样本Id,还有subdate()函数的用法,耗时644 ms, 在Rising Temperature的MySQL提交中击败了51.93% 的用户,代码如下。

select w1.Id from Weather w1, Weather w2 where subdate(w1.RecordDate,1) = w2.RecordDate and w1.Temperature > w2.Temperature

结尾

解法1、解法2、解法3:https://blog.csdn.net/wal1314520/article/details/80115738

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/83269947