How do I find the entire tree given a node of a tree?
Example of tree:
100
101 102
1010 1011 1020 1021
select level, employee_id
Why not just:
select level, employee_id, last_name, manager_id ,
connect_by_root manager_id as root_id
from employees
connect by prior employee_id = manager_id
start with manager_id = 100
Here is a fiddle
EDIT
Here is another try (After understanding the full problem):
with t as (
select case when mgr.employee_id is null then
1 else 0 end is_root, emp.employee_id employee, emp.manager_id manager, emp.last_name last_name
from employees mgr right outer join employees emp
on mgr.employee_id = emp.manager_id
),
tmp as (
select level, employee, last_name, manager ,
connect_by_root manager as root_id,
manager||sys_connect_by_path(employee,
',') cbp
from t
connect by prior employee = manager
start with t.is_root =
1 )
select * from tmp
where tmp.root_id in (select root_id from tmp where employee= 101 or manager = 101)
I checked it with 100
, 101
and 1010
and it worked well
Here is a fiddle
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
start with employee_id in (
select employee_id from employees
where manager_id is null )
You need to first traverse up the tree to get all managers then traverse down to fetch all employees:
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
)
;
See http://www.sqlfiddle.com/#!4/d15e7/18
If the given node might also be the root node, extend the query to include the given node in the list of parent nodes:
Example for non-root node:
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
)
;
Example for root node:
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 at http://www.sqlfiddle.com/#!4/d15e7/32