【发布时间】:2016-11-27 19:35:49
【问题描述】:
我有一个包含分层数据的表,如下所示。
create table tst as
select 1 id, null parent_id from dual union all
select 2 id, 1 parent_id from dual union all
select 3 id, 1 parent_id from dual union all
select 4 id, 2 parent_id from dual union all
select 5 id, 3 parent_id from dual union all
select 6 id, 5 parent_id from dual union all
select 7 id, 6 parent_id from dual union all
select 8 id, 6 parent_id from dual;
使用CONNECT BY 语句遍历层次结构很简单。
我的提取要求是忽略树的简单(竹状)部分,即如果父母只有一个孩子,则两者都被连接并且 ID 被连接(递归应用此规则)。
所以预期的结果是
ID PARENT_ID
---------- ----------
1
2,4 1
3,5,6 1
7 3,5,6
8 3,5,6
UPDATE 或者这也是正确的答案(添加连接的节点列表并重用原始 IDS)
ID PARENT_ID NODE_LST
---------- ---------- ---------
1 1
4 1 2,4
6 1 3,5,6
7 6 7
8 6 8
到目前为止,我设法计算了孩子的数量并构建了孩子数量和 ID 的根的完整路径...
with child_cnt as (
-- child count per parent
select parent_id, count(*) cnt
from tst
where parent_id is not NULL
group by parent_id),
tst2 as (
select
ID, child_cnt.cnt,
tst.parent_id
from tst left outer join child_cnt on tst.parent_id = child_cnt.parent_id),
tst3 as (
SELECT id, parent_id,
sys_connect_by_path(cnt,',') child_cnt_path,
sys_connect_by_path(id,',') path
FROM tst2
START WITH parent_id IS NULL
CONNECT BY parent_id = PRIOR id
)
select * from tst3
;
ID PARENT_ID CHILD_CNT_PATH PATH
---------- ---------- -------------- ------------
1 , ,1
2 1 ,,2 ,1,2
4 2 ,,2,1 ,1,2,4
3 1 ,,2 ,1,3
5 3 ,,2,1 ,1,3,5
6 5 ,,2,1,1 ,1,3,5,6
7 6 ,,2,1,1,2 ,1,3,5,6,7
8 6 ,,2,1,1,2 ,1,3,5,6,8
这表明在 ID 4 和 5 上要跳过一个级别(一个尾随的孩子计数 1),在 ID 6 上跳过 2 级(计数路径中的两个训练)。
但我认为应该有一个更简单的方法来解决这个问题。
【问题讨论】: