字段:a b
表B
字段:e f
拼成新表 , 字段:a b e f
A表和B表记录行数也不同。
如果采取
select A1.a,A1.b,B1.e ,B1.f from (select ROW_NUMBER()over (ORDER BY a) id,a,b from A) A1
INNER JOIN
( select ROW_NUMBER()over (ORDER BY e ) id,e,f from B)B1 ON A1.id=B1.id
这种方法, 右表的行数如果比左表的情况下。记录数就不会完全显示
4 个解决方案
#1
改成这样试试:
SELECT A1.a ,
A1.b ,
B1.e ,
B1.f
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY a ) id ,
a ,
b
FROM A
) A1
FULL JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY e ) id ,
e ,
f
FROM B
) B1 ON A1.id = B1.id
#2
把 inner join 改成 full join 这样重复值不会有吗。而且如果不止两张表,10多张表的情况下怎么办?
#3
可以看看效果是不是楼主想要的
--测试数据
if not object_id(N'Tempdb..#A') is null
drop table #A
Go
Create table #A([a] nvarchar(22),[b] nvarchar(22))
Insert #A
select N'a1',N'b1' union all
select N'a2',N'b2'
GO
if not object_id(N'Tempdb..#B') is null
drop table #B
Go
Create table #B([e] nvarchar(22),[f] nvarchar(22))
Insert #B
select N'e1',N'f1' union all
select N'e2',N'f2' union all
select N'e3',N'f3'
Go
--测试数据结束
SELECT A1.a ,
A1.b ,
B1.e ,
B1.f
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY a ) id ,
a ,
b
FROM #A
) A1
FULL JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY e ) id ,
e ,
f
FROM #B
) B1 ON A1.id = B1.id
#4
用full join吧
#1
改成这样试试:
SELECT A1.a ,
A1.b ,
B1.e ,
B1.f
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY a ) id ,
a ,
b
FROM A
) A1
FULL JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY e ) id ,
e ,
f
FROM B
) B1 ON A1.id = B1.id
#2
把 inner join 改成 full join 这样重复值不会有吗。而且如果不止两张表,10多张表的情况下怎么办?
#3
可以看看效果是不是楼主想要的
--测试数据
if not object_id(N'Tempdb..#A') is null
drop table #A
Go
Create table #A([a] nvarchar(22),[b] nvarchar(22))
Insert #A
select N'a1',N'b1' union all
select N'a2',N'b2'
GO
if not object_id(N'Tempdb..#B') is null
drop table #B
Go
Create table #B([e] nvarchar(22),[f] nvarchar(22))
Insert #B
select N'e1',N'f1' union all
select N'e2',N'f2' union all
select N'e3',N'f3'
Go
--测试数据结束
SELECT A1.a ,
A1.b ,
B1.e ,
B1.f
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY a ) id ,
a ,
b
FROM #A
) A1
FULL JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY e ) id ,
e ,
f
FROM #B
) B1 ON A1.id = B1.id
#4
用full join吧