Here is the table:
create table test_table ( id integer not null, name char(1) not null, parent_id integer, sum integer not null); INSERT INTO test_table VALUES(1, 'A', null, 300); INSERT INTO test_table VALUES(11, 'B', 1, 2340); INSERT INTO test_table VALUES(111, 'C', 11, 3200); INSERT INTO test_table VALUES(22, 'D', 1, 7540); INSERT INTO test_table VALUES(2, 'E', null, 6300); INSERT INTO test_table VALUES(3, 'F', 2, 8600); INSERT INTO test_table VALUES(101, 'G', 3, 3800); INSERT INTO test_table VALUES(102, 'H', 3, 9700); Here is the code:
SELECT distinct sum, name, CASE level WHEN 1 THEN (SELECT SUM(SUM) FROM test_table WHERE level > 1 START WITH parent_id is null CONNECT BY prior id = parent_id) WHEN 2 THEN (SELECT SUM(SUM) FROM test_table WHERE level > 2 START WITH parent_id is null CONNECT BY prior id = parent_id) WHEN 3 THEN null END AS SUM_SUM FROM test_table START WITH parent_id is null CONNECT BY prior id = parent_id order by name; There is a specific question, there is a more general. Specific: how to calculate the salary of all subordinates, while the salary of the head is not taken into account. Common - how to separate the subordinates of one boss from another? Because in this query, an outpourse of all subordinates is issued, having a level greater than that of the superior.
Sample output:
CREATE TABLE result_tbl ( id integer not null, name char(1) not null, parent_id integer, sum integer not null); INSERT INTO result_tbl VALUES(1, 'A', null, 12080); INSERT INTO result_tbl VALUES(11, 'B', 1, 3200); INSERT INTO result_tbl VALUES(111, 'C', 11, 0); INSERT INTO result_tbl VALUES(22, 'D', 1, 0); INSERT INTO result_tbl VALUES(2, 'E', null, 22100); INSERT INTO result_tbl VALUES(3, 'F', 2, 13500); INSERT INTO result_tbl VALUES(101, 'G', 3, 9700); INSERT INTO result_tbl VALUES(102, 'H', 3, 0);