选择记录作为配对父子

时间:2013-10-31 04:59:29

标签: sql oracle11g

记录将保存为与pairkey列关联的同一个表中的父子,然后父母将分为两个与scndleg列相关联的分支。也就是说,将有两个父帖与scndleg列相互关联,每个父母都会在seqnno列中拥有pairkey个父级的子女。

看看这个fiddle

我需要选择一个完整的批次

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

然后其他批次遵循fiddle

中显示的相同模式等

1 个答案:

答案 0 :(得分:0)

编辑查询的新版本(最后链接到SQLFiddle):

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
;

输出:

    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