Table T represents a tree. Every record is a node and each node has only one parent.
This query calculates the SUM() of each branch for every node.
WITH t AS
(SELECT 1 id, NULL parent_id, NULL value FROM dual UNION ALL
SELECT 10 id, 1 parent_id, 1000 value FROM dual UNION ALL
SELECT 20 id, 1 parent_id, 2000 value FROM dual UNION ALL
SELECT 30 id, 10 parent_id, 3000 value FROM dual UNION ALL
SELECT 40 id, 10 parent_id, 4000 value FROM dual UNION ALL
SELECT 50 id, 20 parent_id, 5000 value FROM dual UNION ALL
SELECT 60 id, 1 parent_id, 6000 value FROM dual UNION ALL
SELECT 70 id, 60 parent_id, 7000 value FROM dual UNION ALL
SELECT 80 id, 70 parent_id, 8000 value FROM dual
) SELECT CAST(LPAD(' ', (LEVEL-1)*4) || ID AS VARCHAR2(20)) id
,VALUE self_value
,(SELECT SUM (value)
FROM t t2
CONNECT BY
PRIOR t2.ID = t2.parent_id
START WITH t2.id = t.id) branch_value
FROM t
CONNECT BY PRIOR t.id = t.parent_id
START WITH t.parent_id IS NULL
ORDER SIBLINGS BY t.id;
ID SELF_VALUE BRANCH_VALUE -------------------- ---------- ------------ 1 36000 10 1000 8000 30 3000 3000 40 4000 4000 20 2000 7000 50 5000 5000 60 6000 21000 70 7000 15000 80 8000 8000 9 rows selected.
I've been trying to achieve the same result of this query using the alternative Subquery Factoring syntax. Any help would be truly appreciated !