You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL Server查询中对统计值求和?附现有查询语句

解决SQL Server中添加统计总和的问题

嘿,我来帮你搞定这个Total统计的需求!你原来想写的sum(count(IR.Id)+count(AR.Id))其实没必要用sum,因为count(IR.Id)和count(AR.Id)已经是分组后每个region对应的聚合值了,直接把这两个值相加就能得到Total,不需要再嵌套sum函数。

修改后的完整查询语句

select 
    R.region_id as Id,
    R.region_name as Name,
    count(IR.Id) as AgencyreportCount,
    count(AR.Id) as IndividualreportCount,
    count(IR.Id) + count(AR.Id) as Total  -- 直接相加两个count结果即可
from region R 
left join governorate G on r.region_id=g.region_id 
left join IndividualReports IR on g.governorate_id=IR.governorate_id 
left join AgencyReports AR on g.governorate_id=AR.governorate_id 
left join AgencyUsers AU on IR.AgencyUserId=AU.Id 
left join Agencies A on AU.AgencyId=A.Id 
where A.Id=1 
Group by R.region_id,R.region_name

补充说明

如果担心左连接带来的null值问题(比如某个region既没有Agencyreport也没有Individualreport时),其实完全不用焦虑——SQL Server里count(null)会直接返回0,所以直接相加的结果是安全的。要是你想更严谨地处理潜在的null场景,也可以写成isnull(count(IR.Id),0) + isnull(count(AR.Id),0) as Total,不过这属于可选的冗余优化,因为count本身不会返回null值。

内容的提问来源于stack exchange,提问作者john derik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:38:19