PostgreSQL计数(布尔表达式)

PostgreSQL计数(布尔表达式),postgresql,count,logical-operators,Postgresql,Count,Logical Operators,在Postgresql中,最好的方法是什么?我想计算字段A中有多少个value=1的计数,以及同一字段A中有多少个value=0的计数 大概是这样的: select count (field1 = value1) as filed1_ok, count (field1 = value2) as filed1_bad, extract(MONTH from rpt_date) AS mth where rpt_date between frdate and todate

在Postgresql中,最好的方法是什么?我想计算字段A中有多少个
value=1
的计数,以及同一字段A中有多少个
value=0
的计数

大概是这样的:

select 
    count (field1 = value1) as filed1_ok, 
    count (field1 = value2) as filed1_bad,
    extract(MONTH from rpt_date) AS mth
where rpt_date between frdate and todate
group by mth
使用计数(条件或空)

true或null
计算结果为
true
false或null
计算结果为
null
。因为
count
不计算空值,这正是您想要的

在其他SQL方言和Postgresql中,可以使用
case

select
    coalesce(sum(case field1 when 1 then 1 end), 0) as filed1_ok,
    coalesce(sum(case field1 when 0 then 1 end), 0) as filed1_bad,
    extract(MONTH from rpt_date) AS mth
where rpt_date between frdate and todate
group by mth

我认为与<代码>计数(条件或NULL)< /COD> PostgreSQL选项相比,它是冗长而不透明的。

select
    coalesce(sum(case field1 when 1 then 1 end), 0) as filed1_ok,
    coalesce(sum(case field1 when 0 then 1 end), 0) as filed1_bad,
    extract(MONTH from rpt_date) AS mth
where rpt_date between frdate and todate
group by mth