/*
then materialized path representation of tree is easy to output: order by path, level
*/
declare @orgchart table (emp varchar(30), path varchar(100))
insert @orgchart
select 'Albert', '1'
union all select 'Bert', '1.2'
union all select 'Chuck', '1.3'
union all select 'Eddie', '1.3.4'
union all select 'Donna', '1.3.5'
union all select 'Fred' ,'1.3.6'
select *, lvl=len(path) - len(replace(path, '.', ''))
from @orgchart
-- show all the staffs and their boss
select staff=subordinate.emp, boss=supervisor.emp
from @orgchart subordinate, @orgchart supervisor
where subordinate.path like supervisor.path + '%'
and subordinate.path > supervisor.path
-- show all the staffs and their aide
-- select staff=supervisor.emp, subordinate.emp
select supervisor.*, subordinate.*
from @orgchart subordinate, @orgchart supervisor
where subordinate.path like supervisor.path + '%'
and subordinate.path > supervisor.path