En rekursiv forespørgsel er vejen at gå:
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;
Det vigtige er at beholde id'et for rodnoden i hver rekursion, så du kan gruppere efter det id i det endelige resultat.