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

4 回答 4

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
于 2012-11-27T02:29:04.967 回答
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

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

于 2012-11-27T02:53:47.437 回答
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);
于 2012-11-27T02:57:12.150 回答
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 对象的完整代码。附言。此代码包含一些不重要的自定义函数,您可能会猜到它们的值。

于 2012-11-27T05:25:08.473 回答