I have a table, SELECT * FROM data
id pred name visual link, for your convenience
--------------------
1 null One
20 null Two <--+
21 20 Three -^
30 null Four <--+
31 30 Five -^ <--+
32 31 Six -^
In which the rows are connected via the pred
column to the id
column. They form only chains and not a tree -- each node has only one or zero successors (if that's important).
I want to add a column init
to the query where the very first element in the chain is shown, i.e.
id pred name init initname
---------------------------------
1 null One 1 One
20 null Two 20 Two
21 20 Three 20 Two
30 null Four 30 Four
31 30 Five 30 Four
32 31 Six 30 Four
- It would be ok if rows with
pred=null
also shownull
forinit
. - The
initname
column is completely optional and I show it here only for demonstration, I only need theid
.
From what I gathered about the connect by
clause I managed a somewhat reverse result, where for each "root" its "child" nodes are listed. I don't know how to "turn the query around".
SELECT id, pred, CONNECT_BY_ROOT id init, LEVEL, CONNECT_BY_ISLEAF "IsLeaf"
FROM data
CONNECT BY PRIOR pred=id
ORDER BY id, level;
Gives the result
id pred init lvl isLeaf
--------------------------
1 null 1 1 1
20 null 20 1 1
20 null 21 2 1
21 20 21 1 0
30 null 30 1 1
30 null 31 2 1
30 null 32 3 1
31 30 31 1 0
31 30 32 2 0
32 31 32 1 0
which somehow represents the the whole "tree", obviously. But alas, "the wrong way around". I'd need for example
id pred init lvl isLeaf
21 20 0 ? ?
instead of
id pred init lvl isLeaf
21 20 21 1 0
If you need data, here is the example data:
create table data ( id number primary key, pred number, name varchar2(100) );
insert into data(id,pred,name) values( 1 , null , 'One');
insert into data(id,pred,name) values( 20, null , 'Two');
insert into data(id,pred,name) values(21, 20 , 'Three');
insert into data(id,pred,name) values(30, null , 'Four');
insert into data(id,pred,name) values(31, 30 , 'Five');
insert into data(id,pred,name) values(32, 31 , 'Six');