Computer Science/SQL
SQL | LeetCode 197. 셀프 조인(Self Join)과 DATE_ADD를 활용한 날짜 비교 문제
올리브한입
2025. 5. 2. 05:09
반응형
기온 데이터가 저장된 Weather 테이블이 주어졌을 때, 전날보다 더 따뜻했던 날짜의 id를 구하는 문제입니다.
Table: Weather
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id is the column with unique values for this table.
There are no different rows with the same recordDate.
This table contains information about the temperature on a certain day.
Write a solution to find all dates' id with higher temperatures compared to its previous dates (yesterday).
Return the result table in any order.
The result format is in the following example.
Example 1:
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 |
+----+
Explanation:
In 2015-01-02, the temperature was higher than the previous day (10 -> 25).
In 2015-01-04, the temperature was higher than the previous day (20 -> 30).
- recordDate를 기준으로 전날 데이터를 찾아야 하므로 DATE_ADD 또는 DATE_SUB 함수가 필요합니다.
- 같은 테이블 내에서 다른 행을 참조해야 하므로 셀프 조인을 사용합니다.
SELECT W1.id
FROM Weather W1
JOIN Weather W2
ON W1.recordDate = DATE_ADD(W2.recordDate, INTERVAL 1 DAY)
WHERE W1.temperature > W2.temperature;
- W1.recordDate = DATE_ADD(W2.recordDate, INTERVAL 1 DAY) 조건은 두 날짜가 1일 차이인 행끼리 조인합니다.
- 온도가 더 높은 경우만 필터링합니다.
반응형