2017-05-24 116 views
0

我有一列需要繼續查找與該列中原始記錄相關聯的最後一條記錄值。SQL遞歸CTE

select rec1, val1 from table1: 

rec1 val1  
a1 t1  
t1 t2  
t2 null 

a2 t7 

t7 null 

該表格(a1,a2)中基本上有2條原始記錄。我需要在我的sql查詢中將t2與a1相關聯,因爲鏈接基於val1列(a1 - > t1 - > t2),直到val1爲null。記錄a2僅與t7鏈接,因爲t7(a2 - > t7)沒有進一步的聯繫。

我希望有一個'簡單'的方法來實現這一點。我嘗試過,但無法取得很大進展。 謝謝

+3

這不是用遊標解決的。相反,你需要一個遞歸CTE。 – JNevill

+0

是的,是的。並且標題也需要進行編輯。 –

+0

我改變了標題。你可以發表一個示例查詢嗎? – user2077110

回答

1

這是一個遞歸的CTE公式。此版本假定沒有循環,並且鏈中沒有超過100個鏈接:

with cte as (
     select rec1, val1, 1 as lev 
     from table1 t1 
     where not exists (select 1 from table1 tt1 where tt1.val1 = t1.rec1) 
     union all 
     select cte.rec1, t.val1, cte.lev + 1 as lev 
     from cte join 
      table1 t1 
      on t1.val1 = cte.rec1 
    ) 
select * 
from (select cte.*, max(lev) over (partition by rec1) as maxlev 
     from cte 
    ) cte 
where maxlev = lev;