[SQL/코드카타] 하루 전 보다 온도가 높은 데이터 값 찾기

전 행과 데이터 비교하기

 

197. Rising Temperature

 

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

 

정답쿼리

SELECT a.id
FROM weather a, weather b
WHERE (a.temperature > b.temperature)
  AND DATEDIFF(a.recordDate, b.recordDate) = 1

 

또 생각해봐야 할 풀이!  -> ⭐️ 윈도우 함수 LAG( ) : 보통 날짜 데이터가 있을 경우에 사용되는 듯

SELECT t.id
FROM
    (SELECT id,
            temperature,
            LAG(temperature, 1) OVER (ORDER BY recordDate) as pre_tem
    FROM weather
    ) t
WHERE t.temperature > t.pre_tem
-- LAG() OVER () 윈도우 함수 결과
| id | temperature | pre_tem |
| -- | ----------- | ------- |
| 1  | 10          | null    |
| 2  | 25          | 10      |
| 3  | 20          | 25      |
| 4  | 30          | 20      |

-- 최죙쿼리 출력 결과
| Id |
| -- |
| 2  |
| 4  |

temperature 과 pre_tem을 비교해서 temperature 이 더 큰 값일 때, id를 가져온다.

윈도우 함수 결과를 from절 서브쿼리에 넣고, 메인쿼리에서 조건을 걸어주면 된다.

🚨 문제점

-- 처음에는 from절 서브쿼리에서 바로 조건을 걸어주려고 시도했으나, 쿼리 실행 순서상 select보다 where가 먼저 실행되어 pre_tem이 참조되지 않는다는 문제가 발생했다.
-- 그래서 서브쿼리에서 조건 필터를 지우고 메인쿼리에 옮겨적었다.

 

LAG( ) 함수 사용법

/* 컬럼명 : 비교할 컬럼명
   기본값 : 이전 값이 없을 경우, 채워넣을 값 (없으면 NULL)
기준_컬럼 : 정렬할 기준 컬럼 (이 순서에 따라 이전 행이 결정) */

LAG(컬럼명, N번째 이전 값, 기본값) OVER (ORDER BY 기준_컬럼)

끝.