27,582
社区成员




select id=coalesce(a.id,b.id,c.id),no=coalesce(a.no,b.no,c.no),a.数学1,b.数学2,c.数学3,[语文]=coalesce(a.语文,b.语文),c.语文3
from 表1 a full join 表2 b on a.id=b.id and a.no=b.no
full join 表3 c on c.id=b.id and c.no=b.no
/*
id no 数学1 数学2 数学3 语文 语文3
----------- ----------- ----------- ----------- ----------- ----------- -----------
1 1 100 NULL NULL 90 NULL
1 2 NULL 85 NULL 70 NULL
1 3 NULL NULL 92 NULL 60
(3 row(s) affected)
*/
create table 表1(id int,no int,数学1 int,语文 int)
create table 表2(id int,no int,数学2 int,语文 int)
create table 表3(id int,no int,数学3 int,语文3 int)
insert 表1 select 1,1,100,90
insert 表2 select 1,2,85,70
insert 表3 select 1,3,92,60
select id=coalesce(a.id,b.id,c.id),no=coalesce(a.no,b.no,c.no),a.数学1,b.数学2,c.数学3,coalesce(a.语文,b.语文),c.语文3
from 表1 a full join 表2 b on a.id=b.id and a.no=b.no
full join 表3 c on c.id=b.id and c.no=b.no
/*
id no 数学1 数学2 数学3 语文3
----------- ----------- ----------- ----------- ----------- ----------- -----------
1 1 100 NULL NULL 90 NULL
1 2 NULL 85 NULL 70 NULL
1 3 NULL NULL 92 NULL 60
(3 row(s) affected)
*/
union all
/*
id no 数学1 数学2 数学3 语文1 语文2 语文3
1 1 100 NULL NULL 90 NULL NULL
1 2 NULL 85 NULL NULL 70 NULL
1 3 NULL NULL 92 NULL NULL 60
*/
create table t1(id int,no int,数学1 int,语文1 int)
insert into t1 select 1,1,100,90
create table t2(id int,no int,数学2 int,语文2 int)
insert into t2 select 1,2,85,70
create table t3(id int,no int,数学3 int,语文3 int)
insert into t3 select 1,3,92,60
go
select id,no,数学1,null as 数学2,null as 数学3, 语文1,null as 语文2, null as 语文3 from t1
union all
select id,no,null as 数学1,数学2,null as 数学3, null as 语文1,语文2, null as 语文3 from t2
union all
select id,no,null as 数学1,null as 数学2,数学3, null as 语文1,null as 语文2, 语文3 from t3
insert into Table select id,no,数学1,null,null,语文,null from 表1;
insert into Table select id,no,null,数学2,null,语文,null from 表2;
insert into Table select id,no,null,null,数学3,null,语文3 from 表3;
declare @t1 table
(
id int,
[no] int,
数学1 int,
语文 int
)
declare @t2 table
(
id int,
[no] int,
数学2 int,
语文 int
)
declare @t3 table
(
id int,
[no] int,
数学3 int,
语文3 int
)
insert @t1 select 1,1,100,90
insert @t2 select 1,2,85,70
insert @t3 select 1,3,92,60
select
id,[no],数学1,NULL as 数学2,NULL as 数学3,语文,NULL as 语文3
from @t1
union all
select
id,[no],NULL as 数学1,数学2,NULL as 数学3,语文,NULL as 语文3
from @t2
union all
select
id,[no], NULL as 数学1,NULL as 数学2,数学3,NULL as 语文,语文3
from @t3