3

如何使用 connect by 获取层次结构的顶部和底部,我有一个存储 id 之间转换的表(ID-> REPLACE_ID),我有兴趣从任何 id 开始获取最新的 id。

--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 开头的组吗?

4

2 回答 2

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
于 2014-08-06T09:29:43.733 回答
2

作为一种(更直接的)方法,您可以简单地按值找到最低id和最高replace_id分组connect_by_root(),如果replace_id始终保证大于id,否则请参阅Lennart 答案

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
于 2014-08-06T09:30:22.790 回答