Hello. As in a recursive query using CTE, preserve the hierarchical structure and at the same time calculate the total salary not only at the top of the hierarchy, but also of all nodes, excluding the lowest ones that have no children. The source table looks like this.
It turned out to achieve the desired result using 2 CTE tables.
With the help of such a request
with C(id_working,salary,RootID,RootID_B) as ( select --0 as lvl, company_2.id_working, company_2.salary, company_2.id_working as RootID, company_2.id_boss as RootID_B from company_2 union all select --lvl+1, company_2.id_working, company_2.salary, C.RootID, C.RootID_B from company_2 inner join C on company_2.id_boss = C.id_working) , t1(lvl,bname, id_boss,id_working,path) as (select 1 AS lvl, t.bname, t.id_boss, t.id_working, '' AS path from company_2 t where t.id_boss is null union all select lvl+1, t2.bname, t2.id_boss,t2.id_working, ltrim((t1.path||','||t1.bname),',') AS path from company_2 t2 join t1 on t2.id_boss=t1.id_working ) SEARCH DEPTH FIRST BY path SET orderval select S_2.tree, S.sumsal, S_2.path --orderval --S_2.bname --RPAD('.', (lvl-1)*2, '.') || id AS tree, --C.lvl from company_2 full join ( select RootID,RootID_B, (sum(salary)-min(salary)) as sumsal, count(salary) as count_sal from C group by RootID, RootID_B having count(salary)>1 ) S on company_2.id_working = S.RootID full join (select orderval, id_working,RPAD(' ', (lvl-1)*2, ' ') || bname AS tree, path from t1) S_2 on company_2.id_working=S_2.id_working order by S_2.orderval [1]: https://i.stack.imgur.com/OiMVM.jpg [2]: https://i.stack.imgur.com/utIKf.jpg But how to achieve the same results with 1 CTE?

