LAG
結果セット内の前の行の値を返します。
関連情報: LEAD
構文
LAG(
expression
[, offset ]
[, default ]
)
OVER (
[ PARTITION BY partition_expression ]
ORDER BY sort_expression
)
引数:
expression: 評価するカラムまたは式offset: 現在の行より前の行数(デフォルト: 1)default: 前の行が存在しない場合に返す値(デフォルト: NULL)
注意:
- 負の offset 値は LEAD 関数と同様に動作します
- offset がパーティション境界を超える場合は NULL を返します
例
-- Create sample data
CREATE TABLE scores (
student VARCHAR(20),
test_date DATE,
score INT
);
INSERT INTO scores VALUES
('Alice', '2024-01-01', 85),
('Alice', '2024-02-01', 90),
('Alice', '2024-03-01', 88),
('Bob', '2024-01-01', 78),
('Bob', '2024-02-01', 82),
('Bob', '2024-03-01', 85);
各学生について前回のテストのスコアを取得します:
SELECT student, test_date, score,
LAG(score) OVER (PARTITION BY student ORDER BY test_date) AS previous_score
FROM scores
ORDER BY student, test_date;
結果:
student | test_date | score | previous_score
--------+------------+-------+---------------
Alice | 2024-01-01 | 85 | NULL
Alice | 2024-02-01 | 90 | 85
Alice | 2024-03-01 | 88 | 90
Bob | 2024-01-01 | 78 | NULL
Bob | 2024-02-01 | 82 | 78
Bob | 2024-03-01 | 85 | 82
2 回前のテストのスコアを取得します:
SELECT student, test_date, score,
LAG(score, 2, 0) OVER (PARTITION BY student ORDER BY test_date) AS score_2_tests_ago
FROM scores
ORDER BY student, test_date;
結果:
student | test_date | score | score_2_tests_ago
--------+------------+-------+------------------
Alice | 2024-01-01 | 85 | 0
Alice | 2024-02-01 | 90 | 0
Alice | 2024-03-01 | 88 | 85
Bob | 2024-01-01 | 78 | 0
Bob | 2024-02-01 | 82 | 0
Bob | 2024-03-01 | 85 | 78