使用先前值连接先前的值

时间:2016-01-27 14:10:30

标签: sql recursion connect-by

对不起,我试图找到答案,但我发现没有。在我的查询中,我会先前(!)ARNT as parentARTNRPOSNR as parentPOSNR。我尝试了CONNECT_BY_ROOT,但这只是TOP ARTNRPOSNR。比我尝试SYS_CONNECT_BY_PATH(t1.ARTNR, '/') as parentARTNR,但返回所有树。

你知道我该怎么办?

此SQL工作正常,但它没有父值。

SELECT 
    level,
    t1.ARTNR, 
    t1.POSNR
FROM 
    SMSTLPOS t1
START WITH 
    t1.ARTNR = '057516'
CONNECT BY t1.ARTNR = PRIOR t1.KOMPARTNR

我会这样:

SELECT 
 level,
 t1.ARTNR, 
 t1.POSNR,
 t0.ARTNR as parentARTNR,
 t0.POSNR as parentPOSNR
FROM 
 SMSTLPOS t1
START WITH 
 t1.ARTNR = '057516'
CONNECT BY t1.ARTNR = PRIOR t1.KOMPARTNR

或者例如使用update声明变量值...我不知道。

以下是我想在sql server中为Oracle做的事情:

with
  n(KOMPARTNR, ARTIKEL_NR, level, parentARTNR, parentPOSNR) as (
    select SMSTLPOS.KOMPARTNR,
           SMSTLPOS.ARTNR,
           1 as level,
           SMSTLPOS.ARTNR as parentARTNR,
           SMSTLPOS.POSNR as parentPOSNR
      from SMSTLPOS
     WHERE SMSTLPOS.ARTNR='51269'  -- ARTNR isn't constant  

   UNION ALL

    SELECT SMSTLPOS1.KOMPARTNR,
           SMSTLPOS1.ARTNR,
           n.level + 1,
           n.parentARTNR,
           n.parentPOSNR
      from SMSTLPOS as SMSTLPOS1, n
     WHERE n.KOMPARTNR = SMSTLPOS1.ARTNR
)
SELECT * from n 

1 个答案:

答案 0 :(得分:0)

OMG,我做到了! :D All在SYS_CONNECT_BY_PATH中,但这是格式/ 10/20/30/40我想要(从这个例子)30。首先我使用substr并得到/ 10/20/30,然后我找到了&#的位置39 /'并再次使用前一个substr上的substr。是好还是你有更好的主意?

SELECT 
 level,
 SMSTLPOS.ARTNR, 
 SMSTLPOS.POSNR,
 SUBSTR((SUBSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.POSNR, '/'),0, (INSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.POSNR, '/'), '/',-1)-1))), (INSTR(SUBSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.POSNR, '/'),0, (INSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.POSNR, '/'), '/',-1)-1)), '/', -1))+1) as parentPOSNR,
 SUBSTR((SUBSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.ARTNR, '/'),0, (INSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.ARTNR, '/'), '/',-1)-1))), (INSTR(SUBSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.ARTNR, '/'),0, (INSTR(SYS_CONNECT_BY_PATH(SMSTLPOS.ARTNR, '/'), '/',-1)-1)), '/', -1))+1) as parentARTNR
FROM 
 SMSTLPOS
START WITH 
 SMSTLPOS.ARTNR = '057516'
CONNECT BY SMSTLPOS.ARTNR = PRIOR SMSTLPOS.KOMPARTNR