test表
a b c
小王 1 4
小李 2 3
小刀 test2表
a d e
小王 3 4
小李 6 7需要得到的结果:
小王 1 4 3 4
小李 2 3 6 7
小刀 null null null null
a b c
小王 1 4
小李 2 3
小刀 test2表
a d e
小王 3 4
小李 6 7需要得到的结果:
小王 1 4 3 4
小李 2 3 6 7
小刀 null null null null
b,
c,
d,
e
from test a full join test2 b
on a.a=b.a
if not object_id('test') is null
drop table test
Go
Create table test([a] nvarchar(2),[b] int,[c] int)
Insert test
select N'小王',1,4 union all
select N'小李',2,3 union all
select N'小刀',null,null
Go
if not object_id('test2') is null
drop table test2
Go
Create table test2([a] nvarchar(2),[d] int,[e] int)
Insert test2
select N'小王',3,4 union all
select N'小李',6,7
Go
select isnull(a.a,b.a)a,
b,
c,
d,
e
from test a full join test2 b
on a.a=b.a
/*
a b c d e
---- ----------- ----------- ----------- -----------
小王 1 4 3 4
小李 2 3 6 7
小刀 NULL NULL NULL NULL(3 個資料列受到影響)*/
drop table test
Go
Create table test([a] nvarchar(2),[b] int,[c] int)
Insert test
select N'小王',1,4 union all
select N'小李',2,3 union all
select N'小刀',null,null
Go
if not object_id('test2') is null
drop table test2
Go
Create table test2([a] nvarchar(2),[d] int,[e] int)
Insert test2
select N'小王',3,4 union all
select N'小李',6,7
GoSELECT A,MAX(B)B,MAX(C)C,MAX(D)D,MAX(E)
FROM
(
SELECT A,B,C,NULL AS D,NULL AS E FROM test
UNION ALL
SELECT A,NULL,NULL,D,E FROM test2
) T
GROUP BY A/*
(所影响的行数为 3 行)
(所影响的行数为 2 行)A B C D
---- ----------- ----------- ----------- -----------
小刀 NULL NULL NULL NULL
小李 2 3 6 7
小王 1 4 3 4(所影响的行数为 3 行)警告: 聚合或其它 SET 操作消除了空值。楼主那这个呢
select
isnull(a.a,b.a)as a,
b,
c,
d,
e
from
test L
full outer join
test2 R
on L.a=R.a
test 表中小刀的b,c 是否为null,还是空串,请指明,实现起来略有不同,
不同看了楼上的贴,楼主想已明白如何实现
N'小王' as a, '1' as b, '4' as c
into #Table1
union all
select
N'小李', '2', '3'
union all
select
N'小刀','NULL','NULL'; select
N'小王' as a, '3' as d, '4' as e
into #Table2
union all
select
N'小李', '6', '7'select T1.*, T2.d, T2.e
from #Table1 T1
Left join #Table2 T2 on T1.a = T2.a运行结果
=======================================================
小王 1 4 3 4
小李 2 3 6 7
小刀 NULL NULL NULL NULL
isnull(T.a,T1.a)T,
T.b,
T.c,
T1.d,
T1.e
from test T
full join test2 T1 on T.a=T1.a
b,
c,
d,
e
from test a full join test2 b
on a.a=b.a
from test a,test2 b
where a.a=b.a