197. Rising Temperature

심규원·2024년 8월 19일

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

MySQL

SELECT id
FROM (
    SELECT
        id,
        temperature,
        recordDate,
        LAG(temperature) OVER (ORDER BY recordDate) AS previous_temperature,
        LAG(recordDate) OVER (ORDER BY recordDate) AS previous_recordDate
    FROM Weather
) AS subquery
WHERE DATEDIFF(recordDate, previous_recordDate) = 1 and temperature > previous_temperature;

LAG 함수를 이용해서 이전 행의 값을 비교한다.
온도뿐만이 아니라 날짜도 비교하는데 딱 하루차이만 허용하기 때문에 비교해준다.

DATEDIFF 이 녀석 알게되었다.

속도도 낫배드

SELECT id
FROM (
    SELECT
        id,
        temperature,
        recordDate,
        LAG(temperature) OVER (ORDER BY recordDate) AS previous_temperature,
        LAG(recordDate) OVER (ORDER BY recordDate) AS previous_recordDate
    FROM Weather
) subquery
WHERE (recordDate - previous_recordDate) = 1 AND temperature > previous_temperature;

오라클 역시 거의 동일하나 DATEDIFF 가 없기떄문에 그냥 단순하게 - 연산해서 구해준다.

근데 속도가 너무너무 느리다..

Where 조건문에서 WHERE temperature > previous_temperature and (recordDate - previous_recordDate) = 1;
온도 비교를 먼저 하면 속도가 좀 올라간다.

select a.id
from Weather a
join Weather b on a.recordDate = b.recordDate + 1
where  a.temperature > b.temperature;

그냥 조인할 때 + 1 하고 맞으면 조인시켜주면 되는거였다..

0개의 댓글