表: `Weather`
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id 是这个表的主键
该表包含特定日期的温度信息
编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 id 。
返回结果 不要求顺序 。
输入:
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)
结果
#用lag()开窗函数配合datediff()函数组合
select id
from
(select
id,
temperature,
recordDate,
lag(recordDate,1) over(order by recordDate) as last_date,
lag(temperature,1) over(order by recordDate) as last_temperature
from Weather) a
where temperature > last_temperature and datediff(recordDate, last_date) = 1
lag()函数:
查询当前行向上偏移n行对应的结果,该函数有三个参数:第一个为待查询的参数列名,第二个为向上偏移的位数,第三个参数为超出最上面边界的默认值。
DATEDIFF() 函数
返回两个日期值之间的天数。语法DATEDIFF(date1, date2)