Mysql多计数列明智地各自具有单独的条件

时间:2013-06-15 08:49:40

标签: mysql count

任何人都可以帮我解决mysql查询: -

select 
  (select 
     count(bug_id) 
   from 
     bugs 
   where 
     bugs.priority="P3") as P3count,
  (select count(bug_id) from bugs where bugs.priority="P2") as P2count 
from 
  bugs 
where 
  bugs.product_id=237 and 
  bugs.bug_status='RESOLVED' and 
  bugs.resolution='FIXED' and 
  bugs.creation_ts >= '2013-06-14 09:00:00' and 
  bugs.creation_ts <= '2013-06-16 08:59:59' 
group by 
  priority;

需要结果: -

+---------+----------+ 
| P3count |  P2count |                                                                                                                                          
+---------+----------+                                                                                                                                          
|       7 |     8    |                                                                                                                                      
+---------+----------+

1 个答案:

答案 0 :(得分:1)

不是使用COUNT,而是使用SUM通过为每个匹配的行添加1来计算行数。如果条件为真,则表达式IF(condition,1,0)的计算结果为1,否则为0

SELECT
    SUM(IF(priority="P3",1,0)) P3count,
    SUM(IF(priority="P2",1,0)) P2count,
    ...
FROM bugs
WHERE ...
相关问题