2014-09-13 1 views
1
, 내가 필드 (A)에 value = 1에 얼마나 많은 수를 계산하는 PostgreSQL을에 가장 좋은 방법은 무엇을 원하는

얼마나 많은 수를 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 nulltrue로 평가합니다. false or nullnull으로 평가됩니다. count은 정확히 원하는만큼의 null을 계산하지 않습니다.

다른 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의 옵션에 비해 고려하여 수행 할 수 있습니다.