~고군분투 인생살이~

[197_EASY] Rising Temperature 본문

SQL/LEETCODE

[197_EASY] Rising Temperature

소금깨 2022. 9. 25. 23:16

 

 

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

 

문제 조건

이전 날짜와 비교해서 온도가 더 높은 날짜의 ID를 출력하시오

 

문제 풀이

to_days() : 주어진 날짜를 0000년부터의 일수로 바꾼다. 

select to_days(950501) -> 728779

-- self join
select today.id as id 
from weather yesterday
     left join weather today on yesterday.recordDate = date_sub(today.recordDate,interval 1 day)
where yesterday.temperature < today.temperature

-- cross join (runtime이 오래걸림... cross join이라?) 
select today.id as id 
from weather as today
    cross join weather as yesterday 
where today.temperature > yesterday.temperature 
and to_days(today.recordDate) - to_days(yesterday.recordDate) = 1

 

Comments