Question

I have two tables

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

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

i also have a connect by query

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)

this correctly gives output like the following:

0    node1
1        node2
2            node3
2            node4

so far so good. now i have a requirement to show the full hierarchy for each leaf node - repeating the upper nodes if necessary... something like this:

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

I'm thinking maybe sys_connect_by_path - but not even sure. any thoughts on optimal generation of this kind of output?

Était-ce utile?

La solution

Unfortunately there has been no sample data provided and there can be only speculation.

So here is an example that includes only one table:

-- 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

Which will give us:

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

In order to display full hierarchy for each leaf, we start building our sub-trees starting from

a leaf and going all the way up to the root:

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   

Result:

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

SQLFiddle Demo

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top