这与 Tim Biegeleisen 的回答基本相同,只是完成了测试数据、结果、sql fiddle 和关于分区条件的更正。
注意:一旦蒂姆的答案得到纠正和完成,我很乐意删除这个答案。
测试数据:
create table dbset (id varchar(1), child varchar(1), parent varchar(1) );
insert into dbset values('A','A','A');
insert into dbset values('X','A','X');
insert into dbset values('Z','X','Z');
insert into dbset values('B','6','6');
insert into dbset values('G','6','7');
insert into dbset values('H','7','8');
insert into dbset values('I','8','9');
询问:
SELECT root, lvl
FROM
(
SELECT
connect_by_root id AS root,
level lvl,
row_number() over (PARTITION BY connect_by_root id ORDER BY level DESC) rn
FROM dbset
START WITH id IN ('A','B')
CONNECT BY NOCYCLE child = prior parent
) t
WHERE rn = 1;
结果:
| ROOT | LVL |
|------|-----|
| A | 3 |
| B | 4 |
Sql 小提琴:http ://sqlfiddle.com/#!4/37c70/8