PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

somma gerarchica in PostgreSQL

In PostgreSQL puoi usare CTE ricorsive (Common Table Expression) per percorrere gli alberi nelle tue query.

Ecco due link rilevanti nei documenti:

MODIFICA

Poiché non è richiesta alcuna sottoselezione, potrebbe funzionare un po' meglio su un set di dati più grande rispetto alla query di Arion.

WITH RECURSIVE children AS (
    -- select leaf nodes
    SELECT id, value, parent
        FROM t
        WHERE value IS NOT NULL
    UNION ALL
    -- propagate values of leaf nodes up, adding rows 
    SELECT t.id, children.value, t.parent
        FROM children JOIN t ON children.parent = t.id
)
SELECT id, sum(value) 
    FROM children 
    GROUP BY id   -- sum up appropriate rows
    ORDER BY id;