← 中文资源

简体中文版本

递归 CTE 子树工资汇总

递归引用上不允许聚合,Postgres 直接拒绝:递归 CTE 只展开(根, 成员)对,SUM 放到 CTE 外按根分组,每个节点拿到含自己的完整子树工资。

阅读英文原文

实现说明

实际执行的是 SELECT / INSERT / CREATE——employees、subtree 是涉及的对象。 语句实际拼装出的结构:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;通过 2 个 JOIN 把多张表的行拼到同一个结果里;用 SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;UNION 拼接多个查询的结果集;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;强制子行先有父行的 REFERENCES 外键守卫。

使用要点

  • 2 个 JOIN 会让中间结果按表规模相乘,上生产规模的数据前先确认连接键有索引。

常见问题

这里涉及哪些关系(表/CTE)?

引用的是 employees、subtree,2 个 JOIN 把它们连起来。

核心语句

CREATE TABLE employees (
    employee_id int PRIMARY KEY,
    manager_id  int REFERENCES employees(employee_id),
    name        text NOT NULL,
    salary      int  NOT NULL
);
INSERT INTO employees VALUES
    (1, NULL, 'ceo',  5000),
    (2, 1,    'cto',  4000),
    (3, 2,    'dev1', 3000),
    (4, 2,    'dev2', 3000),
    (5, 1,    'coo',  3800);

代码示例

-- subtree salary rollup in a recursive CTE: SUM must sit outside the recursive term
-- Postgres rejects aggregation over the recursive reference, so recursion only expands (root, member) pairs
CREATE TABLE employees (
    employee_id int PRIMARY KEY,
    manager_id  int REFERENCES employees(employee_id),
    name        text NOT NULL,
    salary      int  NOT NULL
);

INSERT INTO employees VALUES
    (1, NULL, 'ceo',  5000),
    (2, 1,    'cto',  4000),
    (3, 2,    'dev1', 3000),
    (4, 2,    'dev2', 3000),
    (5, 1,    'coo',  3800);

WITH RECURSIVE subtree AS (
    -- anchor: every employee is a member of their own subtree
    SELECT employee_id AS root_id, employee_id, salary
    FROM employees

    UNION ALL

    SELECT s.root_id, e.employee_id, e.salary
    FROM employees e
    JOIN subtree s ON e.manager_id = s.employee_id
)
SELECT
    m.employee_id,
    m.name,
    SUM(s.salary) AS subtree_salary   -- includes the employee plus every direct and indirect report
FROM employees m
JOIN subtree s ON s.root_id = m.employee_id
GROUP BY m.employee_id, m.name
ORDER BY subtree_salary DESC;