Вы не указали имя таблицы, поэтому я предполагаю, что она называется table1 .
Вот запрос для поиска конечного узла для каждого узла в вашей иерархии.Обратите внимание, что вы получите несколько дубликатов, если у любого из ваших узлов будет более одного дочернего узла.
-- sample data
with table1 as (select 11 as id, 12 as id_new from dual
union all select 12, 5 from dual
union all select 5, 18 from dual
union all select 18, 17 from dual
union all select 17, 28 from dual
union all select 28, 13 from dual
union all select 25, 31 from dual
union all select 31, 22 from dual
union all select 22, 41 from dual
union all select 41, 33 from dual
union all select 33, 39 from dual
union all select 39, 30 from dual
union all select 30, 45 from dual
union all select 45, 24 from dual)
-- query
select regexp_substr(id_path, '[^>]+', 1, 1) as root,
id_new as id_last
from (select CONNECT_BY_ISLEAF isleaf, sys_connect_by_path(id, '>') as id_path, id_new
from table1
connect by prior id_new = id)
where isleaf = 1
;
Я думаю, что это должно работать как заявление об обновлении, но я не проверял его.
merge into table1 t
using (select regexp_substr(id_path, '[^>]+', 1, 1) root, id_new as id_last
from (select CONNECT_BY_ISLEAF isleaf, sys_connect_by_path(r.id, '>') as id_path, r.id_new
from table1 r
connect by prior r.id_new = r.id)
where isleaf = 1) u
on (t.id = u.root)
when matched then update
set t.id_last = u.id_last;