求教个表合并问题
有两个表
第一个表
A A1
B B1
C C1
第二个表
A A2
C C2
D D2
结果希望是
A A1 A2
B B1
C C1 C2
D D2
[解决办法]
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([x] varchar(6),[y] varchar(6))
insert [a]
select 'A','A1' union all
select 'B','B1' union all
select 'C','C1'
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go
create table [b]([x] varchar(6),[y] varchar(6))
insert [b]
select 'A','A2' union all
select 'C','C2' union all
select 'D','D2'
--c查询语句
select o.xx,isnull(p.y,'')as py , isnull(q.y,'')as qy from
(
select distinct i.xx from
(
select a.x as xx from a
union all
select b.x as xx from b
) i
) o left join a p on o.xx=p.x
left join b q on o.xx=q.x