SQL
こちらも参考に。
ウィンドウ関数 | LEAD
- LEAD関数は、特定の行の次の行の値を取得するために使用する。
次の行の値を取得する
- LEAD関数を使用して、現在の行の次の行の値を取得することができる。
- 例えば、売上データのテーブルがあるとして、このテーブルから、各月の売上と前月の売上を比較することができる。
LEAD(sales) OVER (ORDER BY month DESC) AS previous_month_sales
SELECT
month,
sales,
LEAD(sales) OVER (ORDER BY month DESC) AS previous_month_sales
FROM
sales_data;
month |
sales |
previous_month_sales |
3 |
100 |
200 |
2 |
150 |
150 |
1 |
300 |
null |
特定の行数先の値を取得する
- LEAD関数を使用して、指定した行数先の値を取得することができる。
- 例えば、2か月前の売上を取得する場合は、次のようにする。
LEAD(sales, 2) OVER (ORDER BY month DESC) AS two_months_before_sales
SELECT
month,
sales,
LEAD(sales, 2) OVER (ORDER BY month DESC) AS two_months_before_sales
FROM
sales_data;
month |
sales |
two_months_before_sales |
4 |
100 |
200 |
3 |
150 |
250 |
2 |
200 |
null |
1 |
250 |
null |
条件付きで次の行の値を取得する
- LEAD関数を使用して、特定の条件に基づいて次の行の値を取得することもできる。
- 例えば、売上が特定の閾値を超えた場合のみ次の行の売上を取得する場合は、CASE文と組み合わせて使用する。
SELECT
month,
sales,
CASE
WHEN sales > 1000 THEN LEAD(sales) OVER (ORDER BY month DESC)
ELSE NULL
END AS prev_month_sales_if_above_1000
FROM
sales_data;
month |
sales |
prev_month_sales_if_above_1000 |
2025-03 |
1200 |
800 |
2025-02 |
800 |
NULL |
2025-01 |
1500 |
600 |
2024-12 |
600 |
NULL |
2024-11 |
2000 |
NULL |
パーティションを使用してグループごとに次の行の値を取得する
- LEAD関数は、
PARTITION BY
句を使用して、特定のグループごとに次の行の値を取得することができる。
- 例えば、地域ごとの売上データがある場合、地域ごとに次の月の売上を取得することができる。
LEAD(sales) OVER (PARTITION BY region ORDER BY month DESV) AS prev_month_sales
SELECT
region,
month,
sales,
LEAD(sales) OVER (PARTITION BY region ORDER BY month DESC) AS prev_month_sales
FROM
sales_data;
month |
region |
sales |
prev_month_sales |
2025-03 |
A |
1200 |
800 |
2025-02 |
A |
800 |
1500 |
2025-01 |
A |
1500 |
NULL |
2025-03 |
B |
600 |
900 |
2025-02 |
B |
900 |
700 |
2025-01 |
B |
700 |
NULL |
移動平均の計算に使用する
- LEAD関数を使用して、移動平均を計算することができる。
- 例えば、現在の月と前月の売上の平均を計算する場合は、次のようにする。
(sales + LEAD(sales) OVER (ORDER BY month DESC)) / 2 AS moving_average
SELECT
month,
sales,
(sales + LEAD(sales) OVER (ORDER BY month DESC)) / 2 AS moving_average
FROM
sales_data;
month |
sales |
moving_average |
4 |
400 |
350 |
3 |
300 |
250 |
2 |
200 |
150 |
1 |
100 |
NULL |
Discussion