197.上升的温度

给定一个Weather表,编写一个SQL查询来查找与之前(昨天的)日期相比温度更高的所有日期的id

【LeetCode】197.上升的温度 学习笔记

用到的表和数据SQL:

[sql] view plain copy
  1. -- ----------------------------  
  2. -- Table structure for `weather`  
  3. -- ----------------------------  
  4. DROP TABLE IF EXISTS `weather`;  
  5. CREATE TABLE `weather` (  
  6.  `Id` int(11) DEFAULT NULL,  
  7.  `RecordDate` date DEFAULT NULL,  
  8.  `Temperature` int(11) DEFAULT NULL  
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;  
  10. -- ----------------------------  
  11. -- Records of weather  
  12. -- ----------------------------  
  13. INSERT INTO `weather` VALUES ('1','2015-01-01''10');  
  14. INSERT INTO `weather` VALUES ('2','2015-01-02''25');  
  15. INSERT INTO `weather` VALUES ('3','2015-01-03''20');  
  16. INSERT INTO `weather` VALUES ('4','2015-01-04''30');  

答案:

方法一:我们可以使用MySQL的函数Datadiff来计算两个日期的差值,我们的限制条件是温度高且日期差1,参见代码如下:

[sql] view plain copy
  1. select w1.Id from weather w1  
  2. inner join weather w2 on w1.Temperature > w2.Temperature and DATEDIFF(w1.RecordDate, w2.RecordDate) = 1;  

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

[sql] view plain copy
  1. SELECT w1.Id FROM Weather w1, Weather w2  
  2. WHERE w1.Temperature > w2.Temperature AND TO_DAYS(w1.RecordDate)=TO_DAYS(w2.RecordDate) + 1;  

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

[sql] view plain copy
  1. SELECT w1.Id FROM Weather w1, Weather w2  
  2. WHERE w1.Temperature > w2.Temperature AND SUBDATE(w1.RecordDate, 1) = w2.RecordDate;  

思路:可以使用 datediff 函数,判断日期的差值为1,。

相关文章:

  • 2020-03-26
  • 2021-12-14
  • 2022-01-12
  • 2022-12-23
  • 2021-10-19
  • 2021-08-08
  • 2022-01-07
  • 2021-11-16
猜你喜欢
  • 2021-11-20
  • 2022-12-23
  • 2021-12-13
  • 2021-10-29
  • 2021-08-03
  • 2022-12-23
  • 2021-08-28
相关资源
相似解决方案