Първо трябва да преминете нагоре по дървото, за да получите всички мениджъри, след което да преминете надолу, за да извлечете всички служители:
select level, employee_id, last_name, manager_id ,
connect_by_root employee_id as root_id
from employees
connect by prior employee_id = manager_id -- down the tree
start with manager_id in ( -- list up the tree
select manager_id
from employees
connect by employee_id = prior manager_id -- up the tree
start with employee_id = 101
)
;
Вижте http://www.sqlfiddle.com/#!4/d15e7/18
Редактиране:
Ако даденият възел може също да е основният възел, разширете заявката, за да включи дадения възел в списъка с родителски възли:
Пример за не-root възел:
select distinct employee_id, last_name, manager_id
from employees
connect by prior employee_id = manager_id -- down the tree
start with manager_id in ( -- list up the tree
select manager_id
from employees
connect by employee_id = prior manager_id -- up the tree
start with employee_id = 101
union
select manager_id -- in case we are the root node
from employees
where manager_id = 101
)
;
Пример за основен възел:
select distinct employee_id, last_name, manager_id
from employees
connect by prior employee_id = manager_id -- down the tree
start with manager_id in ( -- list up the tree
select manager_id
from employees
connect by employee_id = prior manager_id -- up the tree
start with employee_id = 100
union
select manager_id -- in case we are the root node
from employees
where manager_id = 100
)
;
Fiddle на http://www.sqlfiddle.com/#!4/d15e7/32