Skip to main content

LeetCode 197. Rising Temperature SQL Solution

Problem

LeetCode SQL Problem

  1. Rising Temperature

Weather table

idrecordDateTemperature
12015-01-0110
22015-01-0225
32015-01-0320
42015-01-0430
52015-01-0530
62015-01-0629

Solution - Self Join Weather Table

Rising Temperature
-- Self Join Weather table. Alias 'P' for Previous Day. Alias 'C' for Current Day.
SELECT C.id
FROM Weather AS P
INNER JOIN Weather AS C ON DATE_ADD(P.recordDate, INTERVAL 1 DAY) = C.recordDate
AND C.Temperature > P.Temperature

Query Output

id
2
4

Solution - Lag() Window Function

Rising Temperature
-- Use Lag() window function to get the previous day's temperature
WITH WeatherPlusPrevDayTemp
AS (
SELECT *
,lag(Temperature) OVER (
ORDER BY recordDate
) AS PrevDayTemperature
FROM Weather
)
SELECT id
FROM WeatherPlusPrevDayTemp
-- Find all dates' id with higher temperature compared to yesterday
WHERE Temperature > PrevDayTemperature

Query Output

id
2
4