PostgreSQL计数(布尔表达式)

时间:2014-09-13 00:35:09

标签: 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
group by mth

1 个答案:

答案 0 :(得分:2)

使用count(condition or null)

select
    count(field1 = 1 or null) as filed1_ok,
    count(field1 = 0 or null) as filed1_bad,
    extract(MONTH from rpt_date) AS mth
where rpt_date between frdate and todate
group by mth

true or null评估为truefalse or 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

count(condition or null) Postgresql选项相比,我认为它冗长且不透明。