Rekurzivní dotaz je cesta:
with recursive tree as (
select node, parent, length, node as root_id
from network
where parent is null
union all
select c.node, c.parent, c.length, p.root_id
from network c
join tree p on p.node = c.parent
)
select root_id, array_agg(node) as edges_in_group, sum(length) as total_length
from tree
group by root_id;
Důležité je zachovat id kořenového uzlu v každé rekurzi, abyste mohli seskupit podle tohoto id v konečném výsledku.