LeetCode--197.上升的溫度

2020-10-04 16:00:09

在這裡插入圖片描述

建表

-- ----------------------------
-- Table structure for `weather`
-- ----------------------------
DROP TABLE IF EXISTS `weather`;
CREATE TABLE `weather` (
 `Id` int(11) DEFAULT NULL,
 `RecordDate` date DEFAULT NULL,
 `Temperature` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of weather
-- ----------------------------
INSERT INTO `weather` VALUES ('1','2015-01-01', '10');
INSERT INTO `weather` VALUES ('2','2015-01-02', '25');
INSERT INTO `weather` VALUES ('3','2015-01-03', '20');
INSERT INTO `weather` VALUES ('4','2015-01-04', '30');

第一種思路,Datadiff來計算兩個日期的差值,然後條件是溫度高且差一天

-- w1當做今天,w2當做昨天,今天溫度比昨天高,且相差一天
select w1.* from weather w1, weather w2
 where w1.Temperature > w2.Temperature
 and DATEDIFF(w1.RecordDate,w2.RecordDate) = 1

第二種思路,TO_DAYS將日期轉換為天,條件同上

select w1.* from weather w1, weather w2
 where w1.Temperature > w2.Temperature
 and TO_DAYS(w1.RecordDate) = TO_DAYS(w2.RecordDate) + 1

第三種思路,可以用Subdate函數來實現日期減1

select w1.* from weather w1, weather w2
 where w1.Temperature > w2.Temperature
 and SUBDATE(w1.RecordDate, 1) = w2.RecordDate