2014-09-13 140 views
1

什麼是PostgreSQL中的最佳方式,我想在一個領域與value = 1算多少算多少數與value = 0在同一領域A.PostgreSQL的計數(布爾表達式)

是這樣的:

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 

回答

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的選項來完成。