递归或加入

时间:2018-03-24 13:20:33

标签: sql-server tsql sql-server-2014

表中有旧的保险单及其新的保单号。就像这样:

OldPol  |   NewPol
------  |  ------
AA1     |   AA2
AA2     |   AA3
AA3     |   AA5
AA5     |   AA9

我需要提出一个查询,该查询应显示所有旧政策的最新政策编号:

OldPol    NewPol
------    -----
AA1        AA9
AA2        AA9
...        AA9
AA5        AA9

尝试递归查询 - 由于允许的最大速度或其他原因而失败,自联接最多只能处理2个级别。有些政策只有2个级别,但有些政策最多有9个级别。

1 个答案:

答案 0 :(得分:0)

textbook recursive cte

declare @T table (old varchar(10), new varchar(10));
insert into @T values 
       ('AA1', 'AA2')
     , ('AA2', 'AA3')
     , ('AA3', 'AA5')
     , ('AA5', 'AA9')
     , ('AB2', 'AB3')
     , ('AB3', 'AB5')
     , ('AC3', 'AC5');
with cte as  
( select t.old,   t.new, cnt = 1  
  from @T t 
  union all 
  select cte.old, t.new, cte.cnt + 1
  from cte 
  join @t t 
    on t.old = cte.new
)
, cte2 as 
( select t.old, t.new, t.cnt 
       , ROW_NUMBER() over (partition by t.old order by t.cnt desc) rn 
    from cte t 
)
select *
from cte2 t 
where t.rn = 1
order by t.old, t.new;