- 论坛徽章:
- 0
|
0004--将多个表的数据按ID合并起来
将多个表的数据按ID合并起来
a
id , value
1 , 11
2 , 21
3 , 31
4 , 41
5 , 51
b
id , value
1 , 12
2 , 22
3 , 32
4 , 42
c , value
1 , 13
2 , 23
3 , 33
5 , 53
d
a , value1 , value2 , value3
1 , 11 , 12 , 13
2 , 21 , 22 , 23
3 , 31 , 32 , 33
4 , 41 , 42 , 0
5 , 51 , 0 , 53
CREATE TABLE #a ([id] [char] (10),[value] [int])
CREATE TABLE #b ([id] [char] (10),[value] [int])
CREATE TABLE #c ([id] [char] (10),[value] [int])
insert into #a(id,value) values(\'1\',11)
insert into #a(id,value) values(\'2\',21)
insert into #a(id,value) values(\'3\',31)
insert into #a(id,value) values(\'4\',41)
insert into #a(id,value) values(\'5\',51)
insert into #b(id,value) values(\'1\',12)
insert into #b(id,value) values(\'2\',22)
insert into #b(id,value) values(\'3\',32)
insert into #b(id,value) values(\'4\',42)
insert into #c(id,value) values(\'1\',13)
insert into #c(id,value) values(\'2\',23)
insert into #c(id,value) values(\'3\',33)
insert into #c(id,value) values(\'5\',53)
select isnull(isnull(#a.id,#b.id),#c.id) id,#a.value value1,#b.value value2,#c.value value3
from #a full join #b on #a.id=#b.id
full join #c on isnull(#a.id,#b.id)=#c.id
drop table #a
drop table #b
drop table #c
id value1 value2 value3
---------- ----------- ----------- -----------
1 11 12 13
2 21 22 23
3 31 32 33
4 41 42 NULL
5 51 NULL 53
(所影响的行数为 5 行)
2个表,
表A
a1 a2
1 9
2 10
3 67
4 33
表B
b1 b2
2 31
4 99
想实现这样
a1 a2 b2
1 9 NULL(或0或不体现任何数)
2 10 31
3 67 NULL(或0或不体现任何数)
4 33 99
谢谢各位指导~
CREATE TABLE #a ([a1] [char] (10),[a2] [int])
CREATE TABLE #b ([b1] [char] (10),[b2] [int])
insert into #a(a1,a2) values(\'1\',9)
insert into #a(a1,a2) values(\'2\',10)
insert into #a(a1,a2) values(\'3\',67)
insert into #a(a1,a2) values(\'4\',33)
insert into #b(b1,b2) values(\'2\',31)
insert into #b(b1,b2) values(\'4\',99)
--显示NULL
--select isnull(#a.a1,#b.b1) a1,#a.a2 a2,#b.b2 b2
--from #a full join #b on #a.a1=#b.b1
--显示0
select #A.a1, #A.a2, isnull(#B.b2, 0)
from #A left join #B on #A.a1 = #B.b1
drop table #a
drop table #b |
|