[Leetcode] Rising Temperature
정답
SELECT Current.id
FROM Weather Current
INNER JOIN Weather Previous ON DATEDIFF(Current.recordDate, Previous.recordDate) = 1
WHERE Current.temperature > Previous.temperature;
✅ Point
- 날짜 하루 차이를 기준으로 INNER JOIN
- Order Of Execution
FROM ~
>INNER JOIN ~
>WHERE ~
>SELECT ~
다른 풀이
- LAG 함수를 이용하여 CTE 선언
LAG(expr [, N[, default]]) [null_treatment] over_clause
- expr: column
- N: N 번째 이전 row. default 1
- default: 행이 존재하지 않을 경우 대체할 값. default NULL
- over_clause:
PARTITION BY
나ORDER BY
사용 가능 (optional)
WITH PreviousWeatherData AS (
SELECT
id,
recordDate,
temperature,
LAG(temperature, 1) OVER (ORDER BY recordDate) AS PreviousTemperature,
LAG(recordDate, 1) OVER (ORDER BY recordDate) AS PreviousRecordDate
FROM
Weather
)
SELECT
id
FROM
PreviousWeatherData
WHERE
temperature > PreviousTemperature
AND
recordDate = DATE_ADD(PreviousRecordDate, INTERVAL 1 DAY);
- LAG 함수로 이전 행에 대한 temperature 과 recordDate 가져오기
OVER
: 개별 row마다 적용되는 범위
- DATE_ADD를 통해 이전 행이 ‘어제’를 가리키고 있는지 점검