我有这个架构:
create table t_hierarchy
(
id number ,
id_sup number ,
id_type number
)
;
insert into t_hierarchy values (1, null, 1);
insert into t_hierarchy values (2, 1, 1);
insert into t_hierarchy values (3, 2, 0);
insert into t_hierarchy values (4, 3, 0);
insert into t_hierarchy values (5, 4, 0);
-- ----
insert into t_hierarchy values (6, 2, 1);
insert into t_hierarchy values (7, 6, 0);
insert into t_hierarchy values (8, 7, 0);
-- ----
insert into t_hierarchy values (9, 2, 1);
insert into t_hierarchy values (10, 9, 0);
insert into t_hierarchy values (11, 10, 0);
-- ----
insert into t_hierarchy values (12, 2, 1);
insert into t_hierarchy values (13, 12, 0);
insert into t_hierarchy values (14, 13, 0);
insert into t_hierarchy values (15, 14, 0);
insert into t_hierarchy values (16, 12, 0);
insert into t_hierarchy values (17, 16, 0);
insert into t_hierarchy values (18, 17, 0);
它表示对象之间的层次结构。 我的目标是为每个 id_type 等于 0 的 id 获取其最后一个祖先。
例如,如果我们在 (3,4,5) 中获取 id,那么 id_type = 0 的最后一个祖先就是 3。
这是所需的输出:
id id_sup id_type last_ancestor
-- ------ ------- -------------
1 1
2 1 1
3 2 0 3
4 3 0 3
5 4 0 3
6 2 1
7 6 0 7
8 7 0 7
9 2 1
10 9 0 10
11 10 0 10
12 2 1
13 12 0 13
14 13 0 13
15 14 0 13
16 12 0 16
17 16 0 16
18 17 0 16
提前致谢,
假设您的层次结构是一棵树,那么您可以使用:
SELECT CONNECT_BY_ROOT id AS id,
CONNECT_BY_ROOT id_sup AS id_sup,
CONNECT_BY_ROOT id_type AS id_type,
CASE id_type WHEN 0 THEN id END AS last_ancestor
FROM t_hierarchy t
WHERE CONNECT_BY_ISLEAF = 1
CONNECT BY
PRIOR id_sup = id
AND PRIOR id_type = 0
AND id_type = 0
哪个输出:
身份证 | ID_SUP | ID_类型 | LAST_ANCESTOR |
---|---|---|---|
1 | 空 | 1 | 空 |
2 | 1 | 1 | 空 |
3 | 2 | 0 | 3 |
4 | 3 | 0 | 3 |
5 | 4 | 0 | 3 |
6 | 2 | 1 | 空 |
7 | 6 | 0 | 7 |
8 | 7 | 0 | 7 |
9 | 2 | 1 | 空 |
10 | 9 | 0 | 10 |
11 | 10 | 0 | 10 |
12 | 2 | 1 | 空 |
13 | 12 | 0 | 13 |
14 | 13 | 0 | 13 |
15 | 14 | 0 | 13 |
16 | 12 | 0 | 16 |
17 | 16 | 0 | 16 |
18 | 17 | 0 | 16 |