col 始祖 for a10
col 末裔 for a10
--■■■Connect_by_RootとConnect_by_IsLeafを使う方法(10g以降)■■■
select Connect_by_Root 親 as 始祖,
嫡男 as 末裔
from 系譜 a
where Connect_by_IsLeaf = 1
start with not exists(select 1 from 系譜 b where a.親=b.嫡男)
connect by prior 嫡男=親;
--■■■分析関数とLevelを組み合わせて葉か判断する方法■■■
select 始祖,末裔
from (select LV,Max(LV) over(partition by 始祖) as MaxLV,始祖,末裔
from (select Level as LV,
substr(sys_connect_by_path(親,','),2,
decode(instr(substr(sys_connect_by_path(親,','),2),','),
0,Length(substr(sys_connect_by_path(親,','),2)),
instr(substr(sys_connect_by_path(親,','),2),',')-1)) as 始祖,
嫡男 as 末裔
from 系譜 a
start with not exists(select 1 from 系譜 b where a.親=b.嫡男)
connect by prior 嫡男=親)
)
where LV=MaxLV;