with Salary_table (Employee_id, Employee_salary) as (
select 1, 4000 from dual union all
select 2, 2500 from dual union all
select 4, 3400 from dual union all
select 5, 4500 from dual union all
select 6, 4300 from dual union all
select 7, 2000 from dual union all
select 8, 1200 from dual union all
select 9, 3100 from dual union all
select 11, 2600 from dual
)
, Employee_table (Employee_id, Employee_name, Manager_id) as (
select 1, 'John', null from dual union all
select 2, 'Phil', null from dual union all
select 3, 'Rayan', 2 from dual union all
select 4, 'Peter', 2 from dual union all
select 5, 'Mark', 2 from dual union all
select 6, 'Steve', 3 from dual union all
select 7, 'Margret', 3 from dual union all
select 8, 'Paul', 3 from dual union all
select 9, 'Joe', null from dual union all
select 10, 'Bose', 9 from dual union all
select 11, 'Jane', 9 from dual
)
select mgr_id, mgr_name, sum(employee_salary) from (
select employee_id, connect_by_root employee_id mgr_id,
connect_by_root employee_name mgr_name
from
employee_table e
start with manager_id is null
connect by prior employee_id = manager_id
)
join salary_table
using(employee_id)
group by mgr_id, mgr_name
order by 1;
MGR_ID MGR_NAM SUM(EMPLOYEE_SALARY)
---------- ------- --------------------
1 John 4000
2 Phil 17900
9 Joe 5700