如何在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
相关产品推荐
相关产品推荐

