Rising Temperature Problem
Description
LeetCode Problem 197.
Table: Weather
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id is the primary key for this table.
This table contains information about the temperature in a certain day.
Write an SQL query to find all dates' id with higher temperature compared to its previous dates (yesterday).
Return the result table in any order.
The query result format is in the following example:
Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
Result table:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
In 2015-01-02, temperature was higher than the previous day (10 -> 25).
In 2015-01-04, temperature was higher than the previous day (30 -> 20).
Solution
Approach: Self Join on the Previous Day
Compare each day with the calendar day before it, not with the previous row. If a date is missing (there is no record for 2015-01-05), the record for 2015-01-06 has no "yesterday" and must not be compared with 2015-01-04.
- Join
Weatherto itself:todayis the day we test,yesterdayis the row whoserecordDateis exactlytoday.recordDate - INTERVAL 1 DAY. Date arithmetic handles month and year boundaries correctly. - Keep the pairs where
today.temperature > yesterday.temperatureand returntoday.id.
The inner join drops days without a record for the day before. Ordering by date and using LAG would compare with the previous row instead, which is wrong when there are gaps, unless you also check that the dates are one day apart.
The Pandas version shifts a copy of the table one day forward, merges it with the original on recordDate, and keeps the rows where the temperature went up.
SELECT today.id
FROM Weather AS today
JOIN Weather AS yesterday
ON yesterday.recordDate = today.recordDate - INTERVAL 1 DAY
WHERE today.temperature > yesterday.temperature;