One - One Code All

Blog Content

同一个sql语句中返回多个count,count(1),count(null)

MySQL PostgreSQL   2020-04-11 21:03:34

特殊场景,同一个SQL返回多个count统计。


方案一

select id,
count(case when 属性 in (1,2) then 1 else 0 end) as sum1,
count(case when  属性 in (3) then 1 else 0 end) as sum2,
sum(case when  属性 in (4,5) then 1 else 0 end) as sum3
from 表名
group by id

 

方案二

 

 SELECT   
count( * ) AS num,  

count(if(字段=1,true,null)) AS sum1,   

count(if(字段=2,true,null)) AS sum2   

FROM 表名 

WHERE  其他条件


count用法


1.count(1)与count(*)得到的结果一致,包含null值。

2.count(字段)不计算null值

3.count(null)结果恒为0



上一篇:Davinci配置postgresql数据源
下一篇: postgresql里json与jsonb中的-> 和 ->>区别

The minute you think of giving up, think of the reason why you held on so long.