반응형
기온 데이터가 저장된 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일 차이인 행끼리 조인합니다.
- 온도가 더 높은 경우만 필터링합니다.
반응형
'Computer Science > SQL' 카테고리의 다른 글
SQL | LeetCode 1280. Nested Join (1) | 2025.05.04 |
---|---|
SQL | LeetCode 1661. Self Join + GROUP BY (3) | 2025.05.03 |
SQL | LeetCode 1581. 방문은 했지만 거래는 없던 고객 찾기 (RIGHT JOIN & GROUP BY 예제) (2) | 2025.05.01 |
SQL | LeetCode 1683. 문자열 길이 함수 (1) | 2025.04.30 |
SQL | LeetCode 584. 조건문으로 필터링하기 (0) | 2025.04.29 |