LoginSignup
0
0

More than 1 year has passed since last update.

Redshiftで再帰処理(WITH RECURSIVE)

Posted at

はじめに

SQLで再帰処理ってなかなか難しいの & Redshiftの例がなかなか見つけられなかったのでここに残します。
再帰処理で作ったテーブルをどう実用につかうの?!みたいなのが大事なのですがそれはまたどこかで。

数値で再帰処理

SQL

WITH RECURSIVE counter_table(cnt) AS (
    -- 初期値指定
    SELECT 1 AS cnt
    UNION ALL
    -- 再帰処理部分
    SELECT cnt + 1 AS cnt FROM counter_table
    -- 終了値指定
    WHERE cnt < 10
)
-- ここが実際のSELECT文
SELECT cnt FROM counter_table;

処理結果

cnt
1
2
3
4
5
6
7
8
9

月次で再帰処理

WITH RECURSIVE calendar(calendar_date) AS (
    -- 初期値指定
    SELECT '2022-01-01'::DATE AS calendar_date
    UNION ALL
    -- 再帰処理部分
    SELECT dateadd(month,1,calendar_date)::DATE AS calendar_date FROM calendar
    -- 終了値指定
    WHERE calendar_date < '2023-12-01'::DATE

)
-- ここが実際のSELECT文
SELECT calendar_date FROM calendar;
calendar_date
2022-01-01
2022-02-01
2022-03-01
2022-04-01
2022-05-01
2022-06-01
2022-07-01
2022-08-01
2022-09-01
2022-10-01
2022-11-01
2022-12-01
2023-01-01
2023-02-01
2023-03-01
2023-04-01
2023-05-01
2023-06-01
2023-07-01
2023-08-01
2023-09-01
2023-10-01
2023-11-01
2023-12-01

文献

大変参考になりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0