日期:2014-05-17 浏览次数:20398 次
--> 测试数据:@表A declare @表A table([ID] varchar(3),[ITEM] int,[NAME] varchar(2)) insert @表A select 'A01',1,'T1' union all select 'A01',2,'T1' union all select 'A02',1,'T1' union all select 'A02',2,'T2' --> 测试数据:@表B declare @表B table([NAME] varchar(2),[ITEM] int) insert @表B select 'T1',0 union all select 'T1',1 union all select 'T2',0 union all select 'T2',1 ;WITH maco AS ( select ROW_NUMBER() OVER (partition BY NAME ORDER BY GETDATE()) AS rid,* from @表A ) SELECT a.ID,a.ITEM,a.NAME,b.* FROM maco a FULL JOIN @表B b ON a.rid-1=b.ITEM AND a.NAME=b.NAME /* ID ITEM NAME NAME ITEM ---- ----------- ---- ---- ----------- A01 1 T1 T1 0 A01 2 T1 T1 1 A02 1 T1 NULL NULL A02 2 T2 T2 0 NULL NULL NULL T2 1 */
------解决方案--------------------
--> 测试数据:@表A declare @表A table([ID] varchar(3),[ITEM] int,[NAME] varchar(2)) insert @表A select 'A01',1,'T1' union all select 'A01',2,'T1' union all select 'A02',1,'T1' union all select 'A02',2,'T2' --> 测试数据:@表B declare @表B table([NAME] varchar(2),[ITEM] int) insert @表B select 'T1',0 union all select 'T1',1 union all select 'T2',0 union all select 'T2',1 ;WITH macoa AS ( select ROW_NUMBER() OVER (partition BY NAME ORDER BY GETDATE()) AS rid,* from @表A ), macob AS ( select ROW_NUMBER() OVER (partition BY NAME ORDER BY GETDATE()) AS rid,* from @表B ) SELECT a.ID,a.ITEM,a.NAME,b.* FROM macoa a FULL JOIN macob b ON a.rid=b.rid AND a.NAME=b.NAME /* ID ITEM NAME rid NAME ITEM ---- ----------- ---- -------------------- ---- ----------- A01 1 T1 1 T1 0 A01 2 T1 2 T1 1 A02 2 T2 1 T2 0 NULL NULL NULL 2 T2 1 A02 1 T1 NULL NULL NULL */