前言
经常会遇到根据不同的条件统计总数的问题,一般有两种写法:count和sum都可以
数据准备:
方法一 :count
代码:
select count( case when age > 20 and age < 25 then 1 else null end ) as cnt0, count( case when age >= 25 and age < 30 then 1 else null end ) as cnt1 from user;
结果:
方法二:sum
代码:
select sum( case when age > 20 and age < 25 then 1 else 0 end ) as cnt0, sum( case when age >= 25 and age < 30 then 1 else 0 end ) as cnt1 from user;
结果:
当然也可以和count代码一样else后面也写为null
select sum( case when age > 20 and age < 25 then 1 else null end ) as cnt0, sum( case when age >= 25 and age < 30 then 1 else null end ) as cnt1 from user;
后记
其实原理很简单,count统计的时候有满足条件的就加1,没有满足的变为null,我们知道聚合函数统计的时候是忽略null值的;而sum原理和coun相似,不过else后面可以是0或者null。
到此这篇关于sql根据不同条件统计总数的文章就介绍到这了,更多相关sql统计总数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论