php count聚合函数加上条件判断读取数据

统计总数示例:

select  a.卫生院顺序号,count(a.ID) as 体检总数,
count(case when a.是否高血压='是' then 1 else null end)as 高血压总数,
count(case when a.是否糖尿病='是' then 1 else null end)as 糖尿病总数,
count(case when a.是否脑卒中='是' then 1 else null end)as 脑卒中总数,
count(case when a.是否冠心病='是' then 1 else null end)as 冠心病总数
from  表  a   where YEAR(a.tjrq) = DATEPART(year, GETDATE())  GROUP BY a.机构号

方法:

sum(case when 字段>0 then 1 else 0 end) as 字段

*注意:count(case when 字段>0 then 1 else 0 end) as 字段

count函数不管记录内容是0或1,它的作用只是计算记录数,如果你要计算次数,用sum(case when 字段>0 then 1 else 0 end) as 字段, 因为你前面计算出来的是0和1的全部次数

或者你用 count(case when 字段>0 then 1 else null end) as 字段这种写法
原文地址:https://www.cnblogs.com/wangyongx/p/15213850.html