如何在此查询中包含等于0的计数?

时间:2012-11-27 02:14:41

标签: sql postgresql postgresql-9.1

我的查询

select state,count(*) from crm_lead group by state;

返回

state   count
done    794
open    560
pending 3
draft   8
cancel  1

但有时我表中没有“取消”任务

state   count
done    794
open    560
pending 4
draft   8

我想在结果中包含count = 0,最好的查询是什么?

4 个答案:

答案 0 :(得分:4)

SELECT  a.STATE , 
        COALESCE(b.count, 0) AS Count
FROM 
    (
        SELECT 'done' AS STATE
        UNION
        SELECT 'open' AS STATE
        UNION
        SELECT 'pending' AS STATE
        UNION
        SELECT 'draft' AS STATE
        UNION
        SELECT 'cancel' AS STATE
    ) a LEFT JOIN 
    (
        SELECT  STATE , 
                count(*) AS count
        FROM    crm_lead
        GROUP BY STATE
    ) b ON a.STATE = b.STATE

答案 1 :(得分:1)

如果您只想确定取消在列表中,您也可以这样做:

select coalesce(t.state, const.state) as state, coalesce(t.cnt, const.cnt) as cnt
from (select state, count(*) as cnt
      from crm_lead
      group by state
     ) t full outer join
     (select 'cancel' as state, 0 as cnt
     ) const
     on t.state = const.state

如果状态列表很长或者您只想确定包含一个特定值,这可能会很方便。

答案 2 :(得分:1)

使用VALUES表达式更简单:

SELECT a.state, COALESCE(b.ct, 0) AS ct
FROM (VALUES('done'), ('open'), ('pending'), ('draft'), ('cancel')) a (state)
LEFT JOIN (
   SELECT state, count(*) AS ct
   FROM   crm_lead
   GROUP  BY state
 ) b USING (state);

答案 3 :(得分:0)

$jsonb = array();
foreach($em as $k => $v) {  
    $q = "
        SELECT  a.STATE , 
        COALESCE(b.count, 0) AS Count
    FROM 
    (
        SELECT 'done' AS STATE
        UNION
        SELECT 'open' AS STATE
        UNION
        SELECT 'pending' AS STATE
        UNION
        SELECT 'draft' AS STATE
        UNION
        SELECT 'cancel' AS STATE
    ) a LEFT JOIN 
    (
        SELECT  STATE , 
                count(*) AS count
        FROM    crm_lead
        WHERE (create_date, create_date) OVERLAPS ('2012-{$nn}-01'::DATE, '2012-{$nn}-{$num}'::DATE)
        GROUP BY STATE
    ) b ON a.STATE = b.STATE
        ";
        $result = retrieve($q);

        $jsona = array();
        $values = array();
        $ev = array();
        foreach($result as $key => $val) {
            $ev[] = $val['count'];
        }

    $jsonb[] = array("label" => $v,"values" =>$ev);
}

$jsona[] = array("label" => array(done,open,pending,draft,cancel),"values" => $jsonb);

这是一个完整的代码,用于构造要返回给JavaScript的JSON对象。 PS。这段代码包含了一些不重要的自定义函数,您可以猜测它们的值。