SQL获取父项的所有子项,并将子项的值添加到父项

时间:2016-10-11 17:36:13

标签: sql oracle

假设我有一张这样的桌子。

ID  Parent  Value
1   NULL    1000
2   1       1000
3   2       1000
4   2       1000
5   2       1000
6   2       1000
7   2       1000
8   1       1000
9   8       1000
10  8       1000
11  8       1000

我想递归地添加给定id的每个子值。正确的输出将是。

ID  Parent  Value
1   NULL    11000
2   1       6000
3   2       1000
4   2       1000
5   2       1000
6   2       1000
7   2       1000
8   1       4000
9   8       1000
10  8       1000
11  8       1000

只有一个“top”父级,其父级值为“Null”。我对SQL很新,所以任何帮助都会受到赞赏。如果有帮助,我正在使用Oracle 11。

1 个答案:

答案 0 :(得分:2)

是的,您可以使用CONNECT_BY_ROOT运算符执行此操作。

基本上,“START WITH”每一行,总结每个根的子节点,然后按root分组。像这样:

with test_data (id, parent, value) as ( 
SELECT 1,   NULL,    1000 FROM DUAL UNION ALL
SELECT 2,   1,       1000 FROM DUAL UNION ALL
SELECT 3,   2,       1000 FROM DUAL UNION ALL
SELECT 4,   2,       1000 FROM DUAL UNION ALL
SELECT 5,   2,       1000 FROM DUAL UNION ALL
SELECT 6,   2,       1000 FROM DUAL UNION ALL
SELECT 7,   2,       1000 FROM DUAL UNION ALL
SELECT 8,   1,       1000 FROM DUAL UNION ALL
SELECT 9,   8,       1000 FROM DUAL UNION ALL
SELECT 10,  8,       1000 FROM DUAL UNION ALL
SELECT 11,  8,       1000 FROM DUAL)
SELECT root_id id, root_parent parent, sum(value) value
FROM ( 
SELECT connect_by_root(id) root_id, connect_by_root(parent) root_parent, value 
FROM test_data td
connect by parent = prior id
-- notice there is no "start with" clause
)
group by root_id, root_parent
order by root_id