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
答案 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
评估为true
。 false 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选项相比,我认为它冗长且不透明。