22,209
社区成员
发帖
与我相关
我的任务
分享
--两种解决方案
if object_id('a') is not null
drop table a
go
create table a
(
a1 int,
a2 int,
a3 int,
a4 int
)
go
if object_id('b') is not null
drop table b
create table b
(
a1 int,
a2 int,
a3 int,
b4 int
)
go
insert into a
select 22,33,44,55
go
insert into b
select 66,77,88,99 union all
select 22,33,44,88
go
select B.A1,B.A2,B.A3,
(case when A.A4 IS NULL then B.A4 else A.A4 end)A4,
(case when A.B4 IS NULL then B.B4 else A.B4 end)B4
from
(
select A1, A2, A3, A4,'' as B4 from A
)A
FULL join
(
select A1, A2, A3, ''as A4,B4 from B
)B ON A.A1=b.A1 and A.A2=B.A2 and A.A3=B.A3
go
--or
with t as
(
select A1, A2, A3, A4,'' as B4 from a
union all
select A1, A2, A3, '',B4 from b
)
select A1, A2, A3,max(A4)A4,max(B4)B4
from t
group by A1, A2, A3
--X
select B.A1,B.A2,B.A3,(CASE WHEN A.A4 IS NULL THEN B.A4 ELSE A.A4 END)A4,
(CASE WHEN A.B4 IS NULL THEN B.B4 ELSE A.B4 END)B4 from
(
select A1, A2, A3, A4,'' as B4 from a
)a
full join
(
select A1, A2, A3, ''as A4,B4 from b
)b ON a.a1=b.a1 and a.A2=b.A2 and a.A3=b.A3
with t1(a,b,c,d)as(
select 22,33,44,55
)
,tc (a,b,c,d) as(
select 66,77,88,99 union all
select 22,33,44,88
)
select b.a,b.b,b.c,coalesce(b.d,a.d),coalesce(a.e,b.e)
from (select a,b,c,d,null e from t1)a full join (select a,b,c,null d,d e from tc)b
on a.a=b.a and a.b=b.b and a.c=b.c
--union 不去重
select A1, A2, A3, A4,'' as B4 from t1
union all
select A1, A2, A3, '',B4 from t2