Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Encontre a árvore inteira da raiz dando qualquer nó


Você precisa primeiro percorrer a árvore para obter todos os gerentes e depois descer para buscar todos os funcionários:
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
     )
;

Consulte http://www.sqlfiddle.com/#!4/d15e7/18

Editar:


Se o nó fornecido também for o nó raiz, estenda a consulta para incluir o nó fornecido na lista de nós pais:

Exemplo para nó não raiz:
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
     )
;

Exemplo para nó raiz:
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
     )
;

Mexa em http://www.sqlfiddle.com/#!4/d15e7/32