在输出中复制整个CONNECT BY分支

时间:2013-08-17 17:06:55

标签: oracle hierarchical-data

我有两张桌子

node
-------------
id
name

edge
--------------
source_node_id
target_node_id

我还有一个按查询连接

SELECT level,lpad(' ',4*(level)) || tn.name
FROM Node sn, Node tn, Edge e
where e.source_node_id = sn.id
and e.target_node_id = tn.id
start with e.source_node_id in (0)
connect by prior e.target_node_id = e.source_node_id
union
select 0, name
from Node n
where id in (0)

这正确地给出了如下输出:

0    node1
1        node2
2            node3
2            node4
到目前为止一切顺利。现在我需要显示每个叶节点的完整层次结构 - 如有必要,重复上层节点......如下所示:

0    node1
1        node2
2            node3
0    node1
1        node2
2            node4

我想的可能是sys_connect_by_path - 但是甚至不确定。关于这种输出的最佳生成的任何想法?

1 个答案:

答案 0 :(得分:2)

不幸的是,没有提供样本数据,只能推测。

所以这是一个仅包含一个表的示例:

-- made up data 
with t1(id1, parent_id, name1) as(
  select 1, null, 'name_1' from dual union all
  select 2, 1,    'name_2' from dual union all
  select 3, 2,    'name_3' from dual union all
  select 4, 2,    'name_4' from dual

), tree as (  -- hierarchical query  
  select id1
       , parent_id
       , concat(lpad('-', level * 3, '-'), name1) as node_name
       , connect_by_isleaf is_leaf
    from t1
   start with parent_id is null
 connect by prior id1 = parent_id
 )

select node_name
   from tree

哪会给我们:

NODE_NAME
-----------------
---name_1
------name_2
---------name_3
---------name_4

为了显示每个叶子的完整层次结构,我们从

开始构建子树

一片叶子,一直到根:

select node_name
     , row_number() over(partition by connect_by_root(t.id1) 
                         order by id1) as subtree_rn
  from tree t
 start with is_leaf = 1
connect by id1 = prior  parent_id   

结果:

NODE_NAME               SUBTREE_RN
-----------------------------------
---name_1               1
------name_2            2
---------name_3         3
---name_1               1
------name_2            2
---------name_4         3

SQLFiddle Demo