内容持续更新…(始于2024年08月03日)
1.问题
Table: Weather
±--------------±--------+
| Column Name | Type |
±--------------±--------+
| id | int |
| recordDate | date |
| temperature | int |
±--------------±--------+
id is the column with unique values for this table.
There are no different rows with the same recordDate.
This table contains information about the temperature on a certain day.
Write a solution to find all dates’ Id with higher temperatures compared to its previous dates (yesterday).
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Weather table:
±—±-----------±------------+
| id | recordDate | temperature |
±—±-----------±------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
±—±-----------±------------+
Output:
±—+
| id |
±—+
| 2 |
| 4 |
±—+
Explanation:
In 2015-01-02, the temperature was higher than the previous day (10 -> 25).
In 2015-01-04, the temperature was higher than the previous day (20 -> 30).
2. 解题思路
方法1:
- 使用窗口函数 LAG:
LAG 函数用于获取当前行之前的行的值。
在这里,我们用 LAG 函数获取前一天的温度。
2. 进行比较:
比较当前行的温度和前一天的温度,如果当前行的温度更高,则选择当前行的 id。
方法2:
- 自连接解法
自连接 Weather 表:
将 Weather 表自连接,将当前行与前一天的行连接起来。 - 比较当前行和前一天的温度:
比较当前行的温度和前一天的温度,如果当前行的温度更高,则选择当前行的 id。
3. 代码
代码1:
SELECT id
FROM (
SELECT
id,
temperature,
LAG(temperature) OVER (ORDER BY recordDate) AS prev_temperature
FROM Weather
) sub
WHERE temperature > prev_temperature;
- 子查询部分:
- LAG(temperature) OVER (ORDER BY recordDate) AS prev_temperature:获取当前行之前一天的温度,并命名为 prev_temperature。
- 选择 id、temperature 和 prev_temperature。
- 外层查询:
- 从子查询的结果中选择 id,其中当天的温度 temperature 大于前一天的温度 prev_temperature。
代码2:
SELECT w1.id
FROM Weather w1
JOIN Weather w2 ON DATE_ADD(w2.recordDate, INTERVAL 1 DAY) = w1.recordDate
WHERE w1.temperature > w2.temperature;
查询解释
- FROM Weather w1:
将 Weather 表命名为 w1,作为当前行。
2. JOIN Weather w2 ON DATE_ADD(w2.recordDate, INTERVAL 1 DAY) = w1.recordDate:
将 Weather 表再次命名为 w2,作为前一天的行。
使用 DATE_ADD 函数将 w2 的日期加上一天,并与 w1 的日期匹配,找到前一天的行。
3. WHERE w1.temperature > w2.temperature:
- 选择那些当天温度比前一天温度高的记录。