LeetCode 197 Rising Temperature

概要

LeetCodeのsql問題、rising-temperatureという問題を解きました URLは以下です(ログインしないと見られません)
https://leetcode.com/problems/rising-temperature/description/

問題文

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.

回答

昨日よりも気温が上がっているレコードを取得する必要があります。
あるレコードより一つ前のレコードを参照する場合、LAG関数を使います。

https://dev.mysql.com/doc/refman/8.0/ja/window-function-descriptions.html#function_lag

LAG関数は第1引数にカラム名、第2引数に何個前のレコードを見るか指定できます。
さらにOVER句のなかでORDER BYで参照する並び順を指定できます。

select
    id
from
    (
        SELECT
            id,
            temperature,
            recodeDate,
            LAG(temperature, 1) OVER (
                ORDER BY
                    recordDate
            ) beforeTemp,
            LAG(recodeDate, 1) OVER (
                ORDER BY
                    recordDate
            ) beforeDate,
        FROM
            Weather
    ) as lagTable
where
    temperature > beforeTemp
    and DATEDIFF(day, recodeDate, beforeDate) = 1

DATEDIFFは日付のDIFFを返す関数です。
最初に昨日であるという条件を忘れて付けなかったので、二日前のレコードを取得してテストが落ちました。ちゃんと考えれていますね、、。