日期:2014-05-19  浏览次数:20658 次

记录合并的问题 来者有分
sql   A
年               月                 数量1
2007           1                   10
2007           2                   20
2007           3                   30

sql   B
年               月                 数量2
2007           1                   100
2007           2                   200
2007           4                   300

如何才能把A和B的记录合为一个
年               月           数量1         数量2
2007           1               10             100
2007           2               20             200
2007           3               30             0
2007           4               0               300

------解决方案--------------------
用full join 就行了
select [年]=isnull[a.年,b.年],
[月]=isnull(a.月,b.月),
[数量1]=isnull(a.数量1,0),--少了一个,
[数量2]=isnull(b.数量2,0)
from a full join b on a.年=b.年 and a.月=b.月
------解决方案--------------------
declare @sqla table(年 int, 月 int,数量1 int)
insert into @sqla select 2007,1,10
union all select 2007,2,20
union all select 2007,3,30


declare @sqlb table (年 int, 月 int,数量2 int)
insert into @sqlb select 2007,1,100
union all select 2007,2,200
union all select 2007,4,300

select 年=isnull(a.年,b.年),月=isnull(a.月,b.月),数量1=isnull(a.数量1,0),数量2=isnull(b.数量2,0) from @sqla a full join @sqlb b on a.年=b.年 and a.月=b.月
order by isnull(a.年,b.年),isnull(a.月,b.月)

年 月 数量1 数量2
----------- ----------- ----------- -----------
2007 1 10 100
2007 2 20 200
2007 3 30 0
2007 4 0 300

(所影响的行数为 4 行)

------解决方案--------------------
Select
IsNull(IsNull(A.年, B.年), C.年) As 年,
IsNull(IsNull(A.月, B.月), C.月) As 月,
IsNull(数量1, 0) As 数量1,
IsNull(数量2, 0) As 数量2,
IsNull(数量3, 0) As 数量3
From A
Full Join B
On A.年 = B.年 And A.月 = B.月
Full Join C
On A.年 = C.年 And A.月 = C.月