表: Weather
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id 是该表具有唯一值的列。
没有具有相同 recordDate 的不同行。该表包含特定日期的温度信息
编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 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 |
+----+
1 数据准备
Create table If Not Exists Weather (id int, recordDate date , temperature int);
insert overwrite table Weather
values (1, '2015-01-01', 10),
(2, '2015-01-02', 25),
(3, '2015-01-03', 20),
(4, '2015-01-04', 30);
2 思路分析
思路一:开窗函数
select
Id
from (select
Id,
if(Temperature - lag1 > 0, 1, 0) flag
from (
select
Id,
RecordDate,
Temperature,
lag(Temperature, 1, null) over (order by RecordDate) lag1
from Weather
) tmp1) tmp2
where flag = 1;
思路二:自连接
-- MySQL 和 hiveSQL 语法都支持的
select
a.id
from weather a, weather b
where a.temperature > b.temperature
and datediff(a.recordDate, b.recordDate) = 1;
-- datediff 日期相减函数;