--■■■再帰with句を使う方法(11gR2以降)■■■
with rec(root役職,役職,上司,LV) as(
select 役職,役職,NULL,1
from 組織
union all
select a.root役職,b.役職,b.上司,LV+1
from rec a,組織 b
where a.役職 = b.上司)
select root役職,nullif(役職,root役職) as 部下
from (select count(*) over(partition by root役職) as cnt,
root役職,役職,LV
from rec)
where cnt = 1 or LV > 1
order by cnt desc,root役職,LV;
--■■■階層問い合わせを使う方法(10g以降)■■■
select root役職,nullif(役職,root役職) as 部下
from (select connect_by_root 役職 as root役職,
役職,Level as LV
from 組織
where connect_by_IsLeaf = 1 or Level > 1
connect by prior 役職 = 上司)
order by count(*) over(partition by root役職) desc,root役職,LV;