如何使用connect by获取层次结构的顶部和底部,我有一个存储id之间转换的表(ID-> REPLACE_ID),我有兴趣从任何id开始获取最新的id。< / p>
--drop table test_connect_by;
create table test_connect_by(ID number, REPLACE_ID NUMBER);
insert into test_connect_by values(1,2);
insert into test_connect_by values(2,3);
insert into test_connect_by values(3,4);
insert into test_connect_by values(51,52);
insert into test_connect_by values(52,53);
insert into test_connect_by values(53,54);
insert into test_connect_by values(55,55);
SELECT id,replace_id, level
FROM test_connect_by
START WITH ID in (1,51)
CONNECT BY PRIOR replace_id = id;
我有兴趣从1-4和51-54获得转换,或者我可以从2开始并获得2-4。有什么我可以分组来识别以1开头的组和以51开头的组吗?
答案 0 :(得分:2)
未经测试,因此可能存在一些错误:
select id, replace_id
from (
SELECT CONNECT_BY_ROOT id as id, replace_id
, row_number() over (partition by CONNECT_BY_ROOT id order by level desc) as rn
FROM test_connect_by
START WITH ID in (1,51)
CONNECT BY PRIOR replace_id = id
) as T
where rn = 1
答案 1 :(得分:2)
作为一种(更直接)的方法,您可以简单地找到id
值的最低replace_id
和最高connect_by_root()
分组,如果replace_id
始终保证更高而不是id
,否则请参阅Lennart answer:
select min(id) as begins
, max(replace_id) as ends
from test_connect_by
start with id in (1, 51)
connect by id = prior replace_id
group by connect_by_root(id)
结果:
BEGINS ENDS
---------- ----------
1 4
51 54