SQL递归CTE

时间:2017-05-24 18:33:44

标签: sql sql-server loops

我有一个列,我需要继续查找与该列中原始记录关联的最后一个记录值。

select rec1, val1 from table1:

rec1   val1    
a1    t1      
t1    t2    
t2    null

a2    t7

t7    null

此表中基本上有2条原始记录(a1,a2)。我需要在我的sql查询中将t2与a1关联,因为链接基于val1列(a1 - > t1 - > t2),直到val1为空。记录a2仅链接到t7,因为t7没有进一步的链接(a2 - > t7)。

我希望有一种'简单'的方法来实现这一目标。我已经尝试但无法取得很大进展。 感谢

1 个答案:

答案 0 :(得分: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;
相关问题