Пожалуйста, найдите запрос ниже
with your_data as (
select 10001 employee_no,'Functional_Manager' team_role, null manager_emp_no from dual union
select 123,'Center_Manager',10001 from dual union
select 10,'Team_Manager',123 from dual union
select 11,'Team_Manager',123 from dual union
select 12,'Team_Manager',123 from dual union
select 1,'Agent',10 from dual union
select 2,'Agent',10 from dual union
select 5,'Agent',11 from dual union
select 6,'Agent',11 from dual union
select 7,'Agent',11 from dual union
select 8,'Agent',12 from dual union
select 456,'Center_Manager',10001 from dual union
select 15,'Team_Manager',456 from dual union
select 9,'Agent',15 from dual),
t1 as (SELECT manager_emp_no, team_role, employee_no as agent_emp_no, sys_connect_by_path( manager_emp_no, ',' ) path
FROM your_data
start with manager_emp_no is null
CONNECT BY PRIOR employee_no = manager_emp_no),
t2 as (select
t1.manager_emp_no,
t1.team_role,
t1.agent_emp_no,
regexp_substr(t1.path, '[^,]+', 1, commas.column_value) as connect_by
from
t1,
table(cast(multiset(select level from dual connect by level <= length (regexp_replace(t1.path, '[^,]+')) + 1) as sys.OdciNumberList)) commas)
SELECT distinct connect_by_root agent_emp_no as manager_emp_no ,connect_by_root team_role as team_role,agent_emp_no
FROM t2
where agent_emp_no in (select employee_no from your_data where team_role = 'Agent')
CONNECT BY PRIOR agent_emp_no = connect_by
order by manager_emp_no desc nulls first, agent_emp_no asc
Вывод
"MANAGER_EMP_NO" "TEAM_ROLE" "AGENT_EMP_NO"
10001 "Functional_Manager" 1
10001 "Functional_Manager" 2
10001 "Functional_Manager" 5
10001 "Functional_Manager" 6
10001 "Functional_Manager" 7
10001 "Functional_Manager" 8
10001 "Functional_Manager" 9
456 "Center_Manager" 9
123 "Center_Manager" 1
123 "Center_Manager" 2
123 "Center_Manager" 5
123 "Center_Manager" 6
123 "Center_Manager" 7
123 "Center_Manager" 8
15 "Team_Manager" 9
12 "Team_Manager" 8
11 "Team_Manager" 5
11 "Team_Manager" 6
11 "Team_Manager" 7
10 "Team_Manager" 1
10 "Team_Manager" 2
9 "Agent" 9
8 "Agent" 8
7 "Agent" 7
6 "Agent" 6
5 "Agent" 5
2 "Agent" 2
1 "Agent" 1