求一条联合查询的sql话语,节省大家时间已写好测试表代码
求一条联合查询的sql语句,节省大家时间已写好测试表代码
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
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
*/
测试
sql
select
------解决方案--------------------
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
------解决方案--------------------
create Table #T1 (id int,c1 varchar(10))
create Table #T2 (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
select a.Id,b.Id,b.c1 from #T1 a
left join
(
select ROW_NUMBER()over(partition by t1id order by id desc)num,* from #T2
) b on a.id=b.T1Id and b.num=1
-------------------------------
Id Id c1
----------- ----------- ----------
1 1 ddd2
2 3 ddd4
3 6 ddd7
4 NULL NULL