Data/SQL

[LeetCode] 197. Rising Temperature

hyunjoo 2025. 6. 6. 21:37

197. Rising Temperature

 

Write a solution to find all dates' id with higher temperatures compared to its previous dates (yesterday). Return the result table in any order.

 

 

Table: Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+

 

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  |
+----+

문제 파악

전날보다 기온이 상승한 날짜의 id를 찾는 문제

 

 

중간 과정

아래 코드로 조인된 테이블을 봤을 때, 오른쪽 테이블(w2)에 왼쪽 테이블(w1)이 조인 되며 w1.recordDate가 하루 앞선 데이터가 join 되는 것이 어떤 것의 규칙에 의한 것인지 헷갈렸다. 

이렇게 작동하는 이유는 datediff(w1.recordDate, w2.recordDate) = 1 에 의한 것으로 

w1.recordDate - w2.recordDate = 1
→ 즉, 'w1.recordDate가 w2.recordDate보다 하루 뒤여야 한다'를 의미하기 때문이다. 

그리고  right join 을 사용하면 on 조건에 맞는 값이 없는 경우 w1의 값은 null 로 채워진다.

select w1.id
from weather w1 
right join weather w2
on datediff(w1.recordDate, w2.recordDate)=1

 

output

| id   | recordDate | temperature | id | recordDate | temperature |
| ---- | ---------- | ----------- | -- | ---------- | ----------- |
| 2    | 2015-01-02 | 25          | 1  | 2015-01-01 | 10          |
| 3    | 2015-01-03 | 20          | 2  | 2015-01-02 | 25          |
| 4    | 2015-01-04 | 30          | 3  | 2015-01-03 | 20          |
| null | null       | null        | 4  | 2015-01-04 | 30          |

 

 

 

정답

이때 where 절에서 w1.temperature > w2.temperature를 비교할 때 null  > 숫자는 FALSE로 평가되어 해당 행은 결과에서 제외된다.

SELECT w1.id
FROM Weather w1
right join Weather w2
on datediff(w1.recordDate, w2.recordDate) = 1
where w1.temperature > w2.temperature

 

반응형