--■■■connect_by_rootを使う方法(10g以降)■■■
select ID,NextID,RootID,
Last_Value(ID) over(partition by RootID order by LV
Rows between Unbounded Preceding and Unbounded Following) as LeafID
from (select ID,NextID,
connect_by_root ID as RootID,
Level as LV
from IDList a
Start With not exists(select 1 from IDList b
where b.NextID = a.ID)
connect by prior NextID = ID);
--■■■sys_connect_by_pathから根を取得する方法■■■
select ID,NextID,RootID,
Last_Value(ID) over(partition by RootID order by LV
Rows between Unbounded Preceding and Unbounded Following) as LeafID
from (select ID,NextID,
to_number(
substr(sys_connect_by_path(to_char(ID),','),2,
decode(instr(substr(sys_connect_by_path(to_char(ID),','),2),','),
0,Length(substr(sys_connect_by_path(to_char(ID),','),2)),
instr(substr(sys_connect_by_path(to_char(ID),','),2),',')-1))) as RootID,
Level as LV
from IDList a
Start With not exists(select 1 from IDList b
where b.NextID = a.ID)
connect by prior NextID = ID);