197.上升的温度
给定一个Weather
表,编写一个
SQL
查询来查找与之前
(
昨天的
)
日期相比温度更高的所有日期的
id
。
用到的表和数据SQL:
- -- ----------------------------
- -- 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');
答案:
方法一:我们可以使用MySQL的函数Datadiff来计算两个日期的差值,我们的限制条件是温度高且日期差1,参见代码如下:
- select w1.Id from weather w1
- inner join weather w2 on w1.Temperature > w2.Temperature and DATEDIFF(w1.RecordDate, w2.RecordDate) = 1;
方法二:下面这种解法我们使用了MySQL的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;
思路:可以使用 datediff 函数,判断日期的差值为1,。