# Write your MySQL query statement below
197. 上升的温度
表: Weather
+---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id 是这个表的主键 该表包含特定日期的温度信息
编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 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)
原站题解
pythondata 解法, 执行用时: 345 ms, 内存消耗: 67.2 MB, 提交时间: 2024-05-27 09:43:59
''' 利用窗口函数shift获取上一条数据的温度进行判断,此外我们还需要注意日期不连续的情况, 所以需要再加一层判断,确保上一条数据日期为昨天。 ''' import pandas as pd def rising_temperature(weather: pd.DataFrame) -> pd.DataFrame: weather.sort_values('recordDate', inplace=True) res = weather[(weather['temperature'] > weather.shift(1)['temperature']) & (weather.shift(1)['recordDate'] == weather['recordDate'] - datetime.timedelta(days=1))] return res[['id']] # 第二步精简点 def rising_temperature2(weather: pd.DataFrame) -> pd.DataFrame: weather.sort_values(by=['recordDate'], inplace=True) res = weather[((weather.recordDate- weather.shift(1).recordDate) == "1days") & (weather.temperature > weather.shift(1).temperature)] return res[['id']]
mysql 解法, 执行用时: 474 ms, 内存消耗: 0 B, 提交时间: 2022-06-06 10:18:40
# Write your MySQL query statement below select w1.Id FROM Weather w1, Weather w2 where w1.Temperature > w2.Temperature AND DATEDIFF(w1.RecordDate, w2.RecordDate) = 1;
mysql 解法, 执行用时: 643 ms, 内存消耗: N/A, 提交时间: 2018-08-22 12:27:08
# Write your MySQL query statement below select w1.Id FROM Weather w1, Weather w2 where w1.Temperature > w2.Temperature AND DATEDIFF(w1.RecordDate, w2.RecordDate) = 1;