有表如下:
表type:
type_id type_name
1 蒙数
2 蒙阅
3 英语
4 政治
5 语文
表info_1:
type_name xsum section
蒙数 2 华中
蒙阅 4 华中
蒙阅 1 西北
表info_2:
type_name ysum section
蒙数 1 华南
蒙阅 1 华南
英语 3 华南
语文 2 华南
蒙阅 4 华中
蒙数 3 西北
蒙阅 1 西北
现希望得到如下结果:
type_name ysum xsum section
蒙数 1 0 华南
蒙阅 1 0 华南
英语 3 0 华南
语文 2 0 华南
蒙数 0 2 华中
蒙阅 4 4 华中
蒙数 3 0 西北
蒙阅 1 1 西北
注:结果中0是在表info_2或者表info_1中不存在的结果中显示为0
这只是测试数据,实际有可能info_1的数据量要大于info_2
请问各位有什么好的实现方法没?在这里先谢过了!!!
表type:
type_id type_name
1 蒙数
2 蒙阅
3 英语
4 政治
5 语文
表info_1:
type_name xsum section
蒙数 2 华中
蒙阅 4 华中
蒙阅 1 西北
表info_2:
type_name ysum section
蒙数 1 华南
蒙阅 1 华南
英语 3 华南
语文 2 华南
蒙阅 4 华中
蒙数 3 西北
蒙阅 1 西北
现希望得到如下结果:
type_name ysum xsum section
蒙数 1 0 华南
蒙阅 1 0 华南
英语 3 0 华南
语文 2 0 华南
蒙数 0 2 华中
蒙阅 4 4 华中
蒙数 3 0 西北
蒙阅 1 1 西北
注:结果中0是在表info_2或者表info_1中不存在的结果中显示为0
这只是测试数据,实际有可能info_1的数据量要大于info_2
请问各位有什么好的实现方法没?在这里先谢过了!!!
(select typename,ysum,0 xsum,section from info_1
union all
select * from info_2
)
group by
type_name,section
xsum=isnull(a.xsum,0),
ysum=isnull(b.ysum,0),
section=case when a.[section] is null then b.[section] else a.[section] end
from info_1 a,info_2 b
where a.[type_name]=b.[type_name]
declare @type table (type_id int,type_name varchar(4))
insert into @type
select 1,'蒙数' union all
select 2,'蒙阅' union all
select 3,'英语' union all
select 4,'政治' union all
select 5,'语文'
--> 测试数据: @info_1
declare @info_1 table (type_name varchar(4),xsum int,section varchar(4))
insert into @info_1
select '蒙数',2,'华中' union all
select '蒙阅',4,'华中' union all
select '蒙阅',1,'西北'
--> 测试数据: @info_2
declare @info_2 table (type_name varchar(4),ysum int,section varchar(4))
insert into @info_2
select '蒙数',1,'华南' union all
select '蒙阅',1,'华南' union all
select '英语',3,'华南' union all
select '语文',2,'华南' union all
select '蒙阅',4,'华中' union all
select '蒙数',3,'西北' union all
select '蒙阅',1,'西北'select type_name=isnull(a.type_name,b.type_name),ysum=isnull(ysum,0),xsum=isnull(xsum,0),section=isnull(a.section,b.section) from @info_1 a full join @info_2 b
on a.type_name=b.type_name and a.section=b.section
isnull(T2.ysum,0) as ysum,
isnull(T1.xsum,0) as xsum,
T_All.section
from (select type_name,section from info_1
union
select type_name,section from info_1) T_All
left join
info_1 T1 on T_All.type_name=T1.type_name and T_All.section=T1.section
left join
info_1 T2 on T_All.type_name=T2.type_name and T_All.section=T2.section
(
select [type_name]=case when a.[type_name] is null then b.[type_name] else a.[type_name] end,
xsum=isnull(a.xsum,0),
ysum=isnull(b.ysum,0),
[section]=case when a.[section] is null then b.[section] else a.[section] end
from info_1 a
full join info_2 b on a.[type_name]=b.[type_name]
) a
group by [type_name],[section]
(select typename,0 ysum,xsum,section from info_1
union all
select typename,ysum,0 xsum from info_2
)
group by
type_name,section