いかおくら自習室のブログ

普段の学習内容などのアウトプット用のブログです

LAG関数_前日との売上の差を求める方法

はじめに

LAG関数を使って、前日との売上などの差分を求める方法を簡単にまとめています。

準備

CREATE TABLE store(
sales_day date
,amount float);

INSERT INTO store VALUES ('2022-01-01', 100);
INSERT INTO store VALUES ('2022-02-01', 200);
INSERT INTO store VALUES ('2022-03-01', 150);
INSERT INTO store VALUES ('2022-04-01', 250);
INSERT INTO store VALUES ('2022-05-01', 300);

クエリ

WITH lag_sales AS ( 
    SELECT
        sales_day
        , amount
        , lag(amount) OVER () AS lag_amount
    FROM
        store
) 
SELECT
    sales_day
    , amount
    , lag_amount
    , amount - lag_amount AS day_before_amount
FROM
    lag_sales;

WITH句でLAG関数で1日ズラしたカラムを作成しておき、 直下のSELECT句でamountとlag_amountの差分を求めています。 OVER句内は省略していますが、ORDER BY入れてソートするカラムを指定できます。

なお、2日ズラす場合は

lag(amount, 2) OVER () AS lag_amount

と記載します。lag引数の値を変えればその分ズラすことが可能です。

出力結果

sales_day  | amount | lag_amount | day_before_amount
-----------+--------+------------+------------------
2022/01/01 |   100  |    NULL    |      NULL
2022/02/01 |   200  |    100     |      100
2022/03/01 |   150  |    200     |      -50
2022/04/01 |   250  |    150     |      100
2022/05/01 |   300  |    250     |      50