日期:2014-05-18  浏览次数:20638 次

急,这两个表要怎么合并
表一:小学表
年级 小学人数
1 200
2 198
3 190
4 195
5 160
6 158

表二:中学表
年级 中学人数
1 500
2 485
3 490

想得到如下表:
年级 小学人数 中学人数
1 200 500
2 198 485
3 190 490
4 195
5 160
6 158



------解决方案--------------------
select a.*,b.中学人数 from 小学表 a left join 中学表 b on a.年级=b.年级
------解决方案--------------------
select a.*, b.中学人数 from 小学表 a,中学表 b
------解决方案--------------------
full join

------解决方案--------------------
select isnull(a.年级,b.年级) 年级 , isnull(a.小学人数,0) 小学人数 , isnull(b.中学人数,0) 中学人数
from 表一 a full join 表二 b on a.年级 = b.年级
------解决方案--------------------
SQL code
create table a(年级 int,小学人数 int)
insert into a values(2,     198)  
insert into a values(3,     190)  
insert into a values(4,     195)  
insert into a values(5,     160)  
insert into a values(6,     158)  
create table b(年级 int,中学人数 int)
insert into b values(1,    500  )
insert into b values(2,    485  )
insert into b values(3,    490  )  
go

select isnull(a.年级,b.年级) 年级 , isnull(a.小学人数,0) 小学人数 , isnull(b.中学人数,0) 中学人数
from a full join b on a.年级 = b.年级
order by a.年级

drop table a,b

/*
年级          小学人数        中学人数        
----------- ----------- ----------- 
1           0           500
2           198         485
3           190         490
4           195         0
5           160         0
6           158         0

(所影响的行数为 6 行)
*/

------解决方案--------------------
declare @表一 table (年级 int ,小学人数 int )
insert into @表一

select 2 , 198 
union all
select 3 , 190 
UNION ALL
select 4 , 195 
UNION ALL
select 5 , 160 
UNION ALL
select 6 , 158 

declare @表二 table (年级 int ,中学人数 int )
insert into @表二 
select 1 , 500 
UNION ALL
select 2 , 485 
union all
select 3 , 490 


select * from (select a.*,b.中学人数 from @表一 a left join @表二 b on a.年级=b.年级
union all
select b.年级,小学人数=0,b.中学人数 from @表二 b where b.年级 not in (select a.年级 from @表一 a))c order by c.年级


结果:
1 0 500
2 198 485
3 190 490
4 195 NULL
5 160 NULL
6 158 NULL

------解决方案--------------------
这里用到了外连接,可以使用左外连接或者右外连接
如果是作外连接,左面的是主表,也就是说主表中的值全部会在连接中出现,而次表中无对应的值则用null替代
在这里我用个左外连接:
select a.*,b.中学人数
from 小学表 left join 中学表
where 小学表.年纪=中学表.年级
------解决方案--------------------
select *,中学人数 from 小学表 letf join 中学表 on 小学表.id=中学表.id
------解决方案--------------------
select isnull(a.年级,b.年级) 年级 , isnull(a.小学人数,0) 小学人数 , isnull(b.中学人数,0) 中学人数
from a full join b on a.年级 = b.年级
order by a.年级

这种比较好。。
------解决方案--------------------
老乌龟的写法,顶一下
select isnull(a.年级,b.年级) 年级 , isnull(a.小学人数,0) 小学人数 , isnull(b.中学人数,0) 中学人数
from a full join b on a.年级 = b.年级
order by a.年级

------解决方案--------------------
应该用全连接
select case when a.年级 is null then b.年级 else a.年级 end 年级,
a.小学人数,b.中学人数 from 小学表 a full join 中学表 b on a.年级=b.年级
------解决方案--------------------