← 中文资源

简体中文版本

递归 CTE 展开周期事件

用递归 CTE 展开周期事件:每条规则自带步长(7 天或 1 个月),从首日推进到 end_date 为止,越界即停不会死循环。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 event_rules、occurrences。 机制上由这些部分组成:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;WHERE 把语句的作用范围收窄到满足条件的行;ORDER BY 固定了输出顺序;UNION 拼接多个查询的结果集;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这个脚本里出现了哪些表?

event_rules、occurrences。

核心语句

INSERT INTO event_rules VALUES
    (1, 'weekly sync',   DATE '2026-01-05', INTERVAL '7 days',  DATE '2026-02-01'),
    (2, 'monthly close', DATE '2026-01-31', INTERVAL '1 month', DATE '2026-04-30');
CREATE TABLE event_rules (
    rule_id   int PRIMARY KEY,
    title     text NOT NULL,
    starts_on date NOT NULL,
    step      interval NOT NULL,
    end_date  date NOT NULL
);

代码示例

-- WITH RECURSIVE expands recurring events: each rule advances by its own step until end_date
CREATE TABLE event_rules (
    rule_id   int PRIMARY KEY,
    title     text NOT NULL,
    starts_on date NOT NULL,
    step      interval NOT NULL,
    end_date  date NOT NULL
);

INSERT INTO event_rules VALUES
    (1, 'weekly sync',   DATE '2026-01-05', INTERVAL '7 days',  DATE '2026-02-01'),
    (2, 'monthly close', DATE '2026-01-31', INTERVAL '1 month', DATE '2026-04-30');

WITH RECURSIVE occurrences AS (
    -- anchor: the first day of each rule (a date, matching the recursive arm's cast)
    SELECT rule_id, title, starts_on AS occurs_on, step, end_date
    FROM event_rules
    UNION ALL
    -- recursive: (occurs_on + step)::date keeps both arms one column type; strictly increasing dates guarantee termination
    SELECT rule_id, title, (occurs_on + step)::date AS occurs_on, step, end_date
    FROM occurrences
    WHERE occurs_on + step <= end_date
)
SELECT rule_id, title, occurs_on::date AS occurs_on
FROM occurrences
ORDER BY rule_id, occurs_on;