【问题标题】:Recursive sum for each row每行的递归总和
【发布时间】:2023-02-12 02:34:35
【问题描述】:

考虑这个测试数据:

CREATE TABLE IF NOT EXISTS area (
    id integer,
    parent_id integer,
    name text,
    population integer
);

INSERT INTO area VALUES
    (1, NULL, 'North America', 0),
    (2, 1, 'United States', 0),
    (3, 1, 'Canada', 39),
    (4, 1, 'Mexico', 129),
    (5, 2, 'Contiguous States', 331),
    (6, 2, 'Non-contiguous States', 2);
id parent_id name population
1 NULL North America 0
2 1 United States 0
3 1 Canada 39
4 1 Mexico 129
5 2 Contiguous States 331
6 2 Non-contiguous States 2

请注意,population(以百万为单位)在这里表示增加的人口,不包括该地区的儿童。

如何查询每一行的递归和?我需要得到这样的东西:

name sum
North America 501
United States 333
Canada 39
Mexico 129
Contiguous States 331
Non-contiguous States 2

【问题讨论】:

    标签: postgresql common-table-expression recursive-query


    【解决方案1】:

    这是我解决它的方法:

    WITH RECURSIVE parent AS (
        SELECT
            *,
            id AS root  -- Emit the root ID
        FROM area
        -- No WHERE clause, since we treat every row as a possible root
        
        UNION ALL   
        
        SELECT
            area.*,
            parent.root  -- Pass the root ID to the children
        FROM area
        JOIN parent ON parent.id = area.parent_id
    )
    SELECT
        name,
        sum
    FROM (
        SELECT
            root,
            SUM(population)
        FROM parent
        GROUP BY root  -- Here is where we need the root IDs
    ) cumulative
    JOIN area ON area.id = cumulative.root;  -- Use the nice names instead of IDs
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2018-07-16
      • 2012-02-14
      • 2012-02-19
      • 2015-08-30
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 2013-11-26
      相关资源
      最近更新 更多