日期:2014-05-17 浏览次数:20515 次
declare @T1 Table(id int,c1 varchar(10))
declare @T2 Table(id int,c1 varchar(10),T1Id int,OrderNo int)
insert into @T1(id,c1)
select 1,'aa' union all
select 2,'aa' union all
select 3,'aa' union all
select 4,'aa'
insert into @T2(Id,c1,T1Id,OrderNo)
select 1,'ddd2',1,1 union all
select 2,'ddd3',2,1 union all
select 3,'ddd4',2,2 union all
select 4,'ddd5',3,1 union all
select 5,'ddd6',3,2 union all
select 6,'ddd7',3,3
select * from @T1
select * from @T2
/*
想要的结果是:
T1.Id T2.Id T2.c1
1 1 'ddd2'
2 3 'ddd4'
3 6 'ddd7'
4 null null
*/
declare @T1 Table(id int,c1 varchar(10))
declare @T2 Table(id int,c1 varchar(10),T1Id int,OrderNo int)
insert into @T1(id,c1)
select 1,'aa' union all
select 2,'aa' union all
select 3,'aa' union all
select 4,'aa'
insert into @T2(Id,c1,T1Id,OrderNo)
select 1,'ddd2',1,1 union all
select 2,'ddd3',2,1 union all
select 3,'ddd4',2,2 union all
select 4,'ddd5',3,1 union all
select 5,'ddd6',3,2 union all
select 6,'ddd7',3,3
select a.id 't1id',b.id 't2id',b.c1 't2c1'
from @T1 a
left join
(select id,c1,T1Id,
row_number() over(partition by T1Id order by id desc) 'rn'
from @T2) b on a.id=b.T1Id and b.rn=1
/*
t1id t2id t2c1
----------- ----------- ----------
1 1 ddd2
2 3 ddd4
3 6 ddd7
4 NULL NULL
(4 row(s) affected)
*/
SELECT a.Id,b.Id,b.c1
FROM @T1 a
OUTER APPLY
(
SELECT TOP 1 Id,c1 FROM @T2 WHERE T1Id=a.id ORDER BY id desc
) b