leetcode197 上升的温度 Rising Temperature

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

创建表和数据:

-- ----------------------------
-- 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');

解法:

1.思路简单。表自连接,找出温度比前一天高的行。

问题的关键是确定日期的前一天。

日期函数: DATEDIFF(date1,date2) ,返回date1与date2之间相差的天数。

SELECT W1.Id
FROM weather AS W1 JOIN weather AS W2 ON (DATEDIFF(W1.RecordDate,W2.RecordDate) = 1 AND W1.Temperature > W2.Temperature)

2.同样,函数: TIMESTAMPDIFF(unit,begin,end),返回begin与end之间相差多少个unit。unit为DAY时,即为相差“天”。

SELECT W2.Id
FROM weather AS W1 JOIN weather AS W2 
ON (TIMESTAMPDIFF(DAY,W1.RecordDate,W2.RecordDate) = 1 AND W1.Temperature < W2.Temperature);

TO_DAYS函数,用来将日期换算成天数

SELECT w1.Id FROM Weather w1, Weather w2
WHERE w1.Temperature > w2.Temperature AND TO_DAYS(w1.RecordDate)=TO_DAYS(w2.RecordDate) + 1;

使用Subdate函数,来实现日期减1

SELECT w1.Id FROM Weather w1, Weather w2
WHERE w1.Temperature > w2.Temperature AND SUBDATE(w1.RecordDate, 1) = w2.RecordDate;

猜你喜欢

转载自www.cnblogs.com/forever-fortunate/p/11723358.html