问题
My query
select state,count(*) from crm_lead group by state;
which return
state count
done 794
open 560
pending 3
draft 8
cancel 1
but sometime when I have no 'cancel' task in my table
state count
done 794
open 560
pending 4
draft 8
I would like to include count = 0 in the result, what is the best query ?
回答1:
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
回答2:
You can also do this, if you only want to be sure that cancel is in the list:
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
This might be handy if the list of states is long or if you only want to be sure that one particular value is included.
回答3:
Simpler with a VALUES expression:
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);
回答4:
$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);
this is a completed code to contruct a JSON object to be returned to the JavaScript. ps. this code included some custom functions which are not important, you may guess the values of them.
来源:https://stackoverflow.com/questions/13576402/how-to-include-count-equal-to-0-on-this-query