使用select,group by和count时,如何获得非空结果集?

时间:2013-02-01 10:56:39

标签: mysql select count group-by

这是当前的查询:

SELECT status.ct_reconcile_status, 
       IFNULL(COUNT(status.ct_reconcile_status), 0) AS sch_change_status_num 
FROM   db_crewops_cm_action status 
WHERE  status.ct_reconcile_status IN ( 'SUCCESS', 'FAILED' ) 
       AND status.updated_ts > UTC_TIMESTAMP() - INTERVAL 60 minute 
GROUP  BY status.ct_reconcile_status; 

我想得到的结果如下:

SUCCESS   5
FAILED    9

没关系。问题是,我可以得到两种状态的结果数为0的情况,在这种情况下我想要这样:

SUCCESS   0
FAILED    0

而不是空结果集(我现在得到的)。我有一个大概的想法,我应该自己加入表或使用WITH子句,但我不知道如何开始。

1 个答案:

答案 0 :(得分:3)

尝试类似:

SELECT a.status AS ct_reconcile_status,
       (IFNULL(b.sch_change_status_num,0) + a.num) AS sch_change_status_num
FROM
  (SELECT 'SUCCESS' AS status, 0 AS num
   UNION
   SELECT 'FAILED', 0) a
LEFT JOIN
  (SELECT status.ct_reconcile_status, 
          COUNT(status.ct_reconcile_status) AS sch_change_status_num 
   FROM   db_crewops_cm_action status 
   WHERE  status.ct_reconcile_status IN ( 'SUCCESS', 'FAILED' ) 
          AND status.updated_ts > UTC_TIMESTAMP() - INTERVAL 60 minute 
   GROUP  BY status.ct_reconcile_status) b
ON a.status = b.ct_reconcile_status

您可以删除status.ct_reconcile_status IN ( 'SUCCESS', 'FAILED' ) AND,但这可能会更慢。