t-sql中的多个连接

时间:2015-06-08 00:03:58

标签: sql-server tsql sql-server-2008-r2

我在查询时遇到了一些问题。我有两张桌子:

declare @t1 table(pat_ref varchar(10),pas_id varchar(10), is_mnor char(1))
declare @t2 table (prev_pat_ref varchar(10),  pat_ref varchar(10))

insert into @t1 
values ('1','111','y')
      ,('5','115','y')
      ,('6','116','y')
      ,('2','112','n')
      ,('3','113','y')
      ,('4','114','n')

insert into @t2 
values ('1','2')
      ,('5','1')
      ,('6','5')
      ,('3','4')

现在我想:

pat_ref pas_id  is_mnor major_ref
1       111     y       112
5       115     y       112
2       112     n       NULL
3       113     y       114
4       114     n       NULL

但是,我的问题是:

 select t1.* 
 , case when t1.is_mnor='y' then t3.pas_id else null  end as major_ref
 from @t1 t1
 left join @t2 t2 on t1.pat_ref=t2.prev_pat_ref
 left join @t1 t3 on t3.pat_ref=t2.pat_ref 

我得到了:

pat_ref pas_id  is_mnor major_ref
1       111     y       112
5       115     y       111 ---this should be 112
2       112     n       NULL
3       113     y       114
4       114     n       NULL

注意:@ t1和@ t2的初始连接列为t1.pat_ref=t2.prev_pat_ref

1 个答案:

答案 0 :(得分:3)

我认为你想从t2获得最底层关系,并在t1中链接这些行。如果这是真的那么你需要递归cte来获得最底部的行,然后是2个连接:

;with cte as(select *, prev_pat_ref as p, 1 as l from @t2
            union all
            select t.*, c.p, c.l + 1 
            from cte c join @t2 t on t.prev_pat_ref = c.pat_ref),
bot as(select *, row_number() over(partition by p order by l desc) rn from cte)

select t1.*, case when t1.is_mnor='y' then t2.pas_id else null end as major_ref 
from @t1 t1
left join bot b on t1.pat_ref = b.p and b.rn = 1
left join @t1 t2 on b.pat_ref = t2.pat_ref

小提琴http://sqlfiddle.com/#!3/9eecb7db59d16c80417c72d1/530