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

如何正确结合COUNT、CASE WHEN与IN实现准确的SQL统计?

问题解决:SQL统计ActiveMatters结果不符

问题原因

count()函数的统计逻辑是计算所有非NULL值的行数。你当前的CASE语句中,不满足条件时返回0,而0属于非NULL值,所以每一行都会被count()统计进去,最终得到总条数4,而非预期的1。

修复方案

有两种可行的修改方式:

方式1:修改CASE语句,不满足条件时返回NULL

把else 0改为else NULL(或直接省略else,CASE默认不满足条件时返回NULL),这样count()只会统计满足条件的行:

select 
m.mclient
, count(mstatus) [Total Matters]
, count(case when m.mstatus in ('OP', 'OI', 'OC', 'OT') then 1 end) as [ActiveMatters]
from matter m
where m.mclient = '075551'
group by m.mclient
order by m.mclient desc

方式2:用sum()替代count()

sum()会对CASE返回的1和0直接求和,满足条件加1,不满足加0,直接得到符合条件的行数:

select 
m.mclient
, count(mstatus) [Total Matters]
, sum(case when m.mstatus in ('OP', 'OI', 'OC', 'OT') then 1 else 0 end) as [ActiveMatters]
from matter m
where m.mclient = '075551'
group by m.mclient
order by m.mclient desc

验证结果

执行上述任意修改后的语句,都会得到你期望的结果:

mclientTotal MattersActiveMatters
07555141

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:42:18