题目
表: Weather
+---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id 是该表具有唯一值的列。 该表包含特定日期的温度信息
编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 id
。
返回结果 无顺序要求 。
结果格式如下例子所示。
示例 1:
输入:
Weather 表:
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
输出:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
解释:
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)
解法
(1).介绍一个函数
date_sub日期减法运算
DATE_SUB(date,INTERVAL expr type)
date:参数是合法的日期表达式。expr 参数是您希望添加的时间间隔。
type的类型和date_add中的type一样。
(2). 解题思路
select e.id Id
from Weather w,Weather e
-- 将e表recordDate列日期减小1天
-- 并且判断一下w表日期行和e表日期行是否相等
where w.recordDate=date_sub(e.recordDate,interval 1 day)
-- 比较e表温度行与w表温度行的大小
-- 如果e表日期减小后 e表温度也大于上一天的温度
-- 则反回e的id
and e.Temperature>w.Temperature