0

Records are being saved as parent-child in the same table linked with pairkey column and then even parents are divided into two legs linked with scndleg column. That is, there will be two parent legs interlinked with scndleg column and each parent will have children having seqnno of parent in pairkey column.

Look at this fiddle

I need to select one complete batch as

Both legs of interlinked parents
UNION
All children of these two parents

and then the other batch following same pattern and so on shown in the fiddle

4

1 回答 1

0

Edit New version of the query (link to SQLFiddle at the end):

SELECT
    seqnno,
    narration,
    pairkey,
    scndleg
  FROM (
    SELECT p.*, LEAST(seqnno, scndleg) related_leg_min_id
      FROM pairs p
  )
START WITH scndleg IS NOT NULL
CONNECT BY pairkey = PRIOR seqnno AND scndleg IS NULL
ORDER BY connect_by_root(related_leg_min_id), scndleg DESC NULLS LAST, pairkey
;

Output:

    SEQNNO NARRATION                   PAIRKEY    SCNDLEG
---------- ------------------------ ---------- ----------
         1 1st leg parent                    1          4 
         4 2nd leg parent                    4          1 
         2 1st leg child                     1            
         3 1st leg child                     1            
         5 2nd leg child                     4            
         6 2nd leg child                     4            
         7 another 1st leg parent            7         10 
        10 another 2nd leg parent           10          7 
         8 another 1st leg child             7            
         9 another 1st leg child             7            
        11 another 2nd leg child            10            
        12 another 2nd leg child            10            

SQLFiddle

于 2013-10-31T08:09:02.790 回答