聚合连接的节点/边集

时间:2015-02-27 05:20:59

标签: postgresql aggregate common-table-expression recursive-query 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);

connected set

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

result

 edges_in_group | total_edges | total_length
----------------+-------------+--------------
 {1,2,3,4,5,6}  |           6 |          7.9
 {7}            |           1 |          1.0
(2 rows)

我甚至不知道从哪里开始。我需要自定义聚合或窗口功能吗?我可以使用WITH RECURSIVE迭代收集连接的边缘吗?我的真实案例是245,000个边缘的流网络。我希望edges_in_group的最大数量小于200,以及几百个聚合组(行)。

1 个答案:

答案 0 :(得分:4)

递归查询是要走的路:

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;

重要的是在每次递归中保留根节点的id,以便您可以在最终结果中按该id进行分组。