34,588
社区成员
发帖
与我相关
我的任务
分享
--原始数据:@T
declare @T table(kid int,lid int,f3 varchar(4),f4 varchar(4),f5 varchar(4))
insert @T
select null,null,null,null,null union all
select 1,2,'a',NULL,'a' union all
select 1,2,NULL,'e','c' union all
select 1,2,'b','b',NULL union all
select 2,9,'u','x','n' union all
select 1,3,'k','f','d'
--借助临时表#T
select id=identity(int,1,1),* into #T from @T
select a.kid,a.lid,f3=isnull(a.f3,b.f3),f4=isnull(a.f4,b.f4),f5=isnull(a.f5,b.f5)
from
(select * from #T a where id=(select min(id) from #T where kid=a.kid and lid=a.lid)) a
join
(select * from #T a where id=(select max(id) from #T where kid=a.kid and lid=a.lid)) b
on a.kid=b.kid and a.lid=b.lid
/*
得到结果
kid lid f3 f4 f5
1 2 a b a
1 3 k f d
2 9 u x n
*/
--删除测试
drop table #T