Mik*_*e T 5 postgresql aggregate recursive-query common-table-expression window-functions
我有一组具有唯一节点的连接边。它们使用父节点连接。考虑以下示例代码和插图:
CREATE TABLE network (
node integer PRIMARY KEY,
parent integer REFERENCES network(node),
length numeric NOT NULL
);
CREATE INDEX ON network (parent);
INSERT INTO network (node, parent, length) VALUES
(1, NULL, 1.3),
(2, 1, 1.2),
(3, 2, 0.9),
(4, 3, 1.4),
(5, 4, 1.6),
(6, 2, 1.5),
(7, NULL, 1.0);
Run Code Online (Sandbox Code Playgroud)

在视觉上,可以识别两组边缘。如何使用 PostgreSQL 9.1 识别这两个组并length求和?预期结果显示:

edges_in_group | total_edges | total_length
----------------+-------------+--------------
{1,2,3,4,5,6} | 6 | 7.9
{7} | 1 | 1.0
(2 rows)
Run Code Online (Sandbox Code Playgroud)
我什至不知道从哪里开始。我需要自定义聚合或窗口函数吗?我可以WITH RECURSIVE用来迭代收集连接的边吗?我的真实案例是一个有 245,000 条边的流网络。我希望最大数量edges_in_group小于 200,以及几百个聚合组(行)。
递归查询是要走的路:
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;
Run Code Online (Sandbox Code Playgroud)
重要的是在每次递归中保留根节点的 id,以便您可以在最终结果中按该 id 进行分组。