Source 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:
WITH sum_bum ( sum, id, parent_id ) AS ( SELECT 0, id, parent_id FROM test_table WHERE parent_id is NULL UNION ALL SELECT s.sum + t.sum, t.id, t.parent_id FROM test_table t INNER JOIN sum_bum s ON ( s.id = t.parent_id ) ) SELECT s.sum, ttt.name FROM sum_bum s join test_table ttt on ttt.id = s.id order by ttt.name; Example output values:
13080 - А 3200 - B NULL - C NULL - D 22100 - E 13500 - F NULL - G NULL - H In a good way, he should consider the salary of all subordinates, but considers the salary only of those who have bosses. Those. all the way around