상세 컨텐츠

본문 제목

Rising Temperature(LeetCode)

SQL/MySQL 문제풀이

by 관재탑 2022. 7. 20. 15:31

본문

https://leetcode.com/problems/rising-temperature/

 

Rising Temperature - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

문제

Table: Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id is the primary key for this table.
This table contains information about the temperature on a certain day.

 

Write an SQL query to find all dates' Id with higher temperatures compared to its previous dates (yesterday).

Return the result table in any order.

The query 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).

 

 

정답쿼리

SELECT t.id AS id
FROM Weather t 
INNER JOIN Weather y on t.recordDate = DATE_ADD(y.recordDate, INTERVAL 1 DAY)
WHERE t.temperature > y.temperature

 

 

해설

  • 왼쪽이 today테이블, 오른쪽이 yesterday테이블이다. 
  • yesterday테이블의 recordDate에 하루 씩 더해서 today테이블의 recordDate와 JOIN해준다.
  • WHERE t.temperature > y.temperature로 오늘의 온도가 어제의 온도보다 높은 today의 id컬럼만 출력해준다.
SELECT *
FROM Weather t 
INNER JOIN Weather y on t.recordDate = DATE_ADD(y.recordDate, INTERVAL 1 DAY)
["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]

 

관련글 더보기

댓글 영역