码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode197 上升的温度 Rising Temperature

时间:2019-10-23 00:01:26      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:ima   where   换算   建表   etc   engine   round   ted   drop   

给定一个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;

 

leetcode197 上升的温度 Rising Temperature

标签:ima   where   换算   建表   etc   engine   round   ted   drop   

原文地址:https://www.cnblogs.com/forever-fortunate/p/11723358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!