SQL server中如何将两个查询结果集做运算

比如:得到各个机构的销售数量及对应的机构名称selectcountascount1,branchfromtable1groupbybranchselectcountasc... 比如:得到各个机构的销售数量及对应的机构名称
select count as count1, branch from table1 group by branch
select count as count2, branch from table2 group by branch
相同机构的数量做运算,怎么实现
展开
 我来答
heley123456
2012-01-13 · 超过17用户采纳过TA的回答
知道答主
回答量:87
采纳率:0%
帮助的人:21.5万
展开全部
select isnull(t1.branch,t2.branch), isnull(t1.count1,0)+isnull(t2.count2,0) as 'countSum'
from (select sum(count) as count1, branch from table1 group by branch) t1 full outer join
(select sum(count) as count2, branch from table2 group by branch)t2 on t1.branch =t2.branch
这个会把所有的,相同的不相同的机构都列出来.
如果只要相同的,一个内连接就行了:
select t1.branch, isnull(t1.count1,0)+isnull(t2.count2,0) as 'countSum'
from (select sum(count) as count1, branch from table1 group by branch) t1 inner join
(select sum(count) as count2, branch from table2 group by branch)t2 on t1.branch =t2.branch
kas68310
推荐于2018-04-11 · TA获得超过3637个赞
知道大有可为答主
回答量:1468
采纳率:33%
帮助的人:1180万
展开全部
将两条查询语句作为子查询的一部分连表.
select t1.count1+t2.count2 as 'countSum',t1.branch
(select count as count1, branch from table1 group by branch)t1
(select count as count2, branch from table2 group by branch)t2 on t1.branch =t2.branch

这种写法有一个潜在的限制,t1中的branch 必须包含t2,所以你的需求一般这么写:
select sum(counts)counts,branch
from(select * from(select count as counts, branch from table1 group by branch)t1
union
select * from(select count as counts, branch from table2 group by branch )t1)t
group by branch
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式