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

197.上升的温度

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

用到的表和数据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,。

猜你喜欢

转载自blog.csdn.net/aanndd77/article/details/80774351