计算计数,然后计算总计数MySql的总和

时间:2016-03-04 11:13:16

标签: php mysql sum

我的查询

$sql = 'SELECT status FROM tablename';

结果

------------
status
------------
assigned
assigned
assigned
assigned
assigned
accepted
accepted
completed
completed
completed
completed
completed

现在我可以找到每个状态的总数

SELECT status, COUNT(status) AS cnt
FROM tname
GROUP BY b.statusName
HAVING (cnt >= 1)

这将给出

status     cnt
--------------
accepted    2
assigned    5
completed   5

如何仅对completedaccepted计数进行求和?

3 个答案:

答案 0 :(得分:2)

当您将条件放在sum()函数中时,这称为条件求和:

SELECT SUM(IF(status IN ('accepted','assigned'),cnt,0)) as sum_of_acc_asg
FROM    
    (SELECT status, COUNT(status) AS cnt
    FROM tname
    GROUP BY b.statusName
    HAVING (cnt > 1)) t

或者您可以使用首先过滤子查询的位置:

SELECT SUM(cnt) as sum_of_acc_asg
FROM    
    (SELECT status, COUNT(status) AS cnt
    FROM tname
    WHERE status IN ('accepted','assigned')
    GROUP BY b.statusName
    HAVING (cnt > 1)) t

答案 1 :(得分:1)

简单,将group by替换为where

SELECT status, COUNT(status) AS cnt
 FROM tname 
 WHERE b.statusName IN ('completed','accepted')
 HAVING (cnt > 1)

答案 2 :(得分:0)

SELECT COUNT(status)AS cnt  从tname  WHERE status ='completed'或status ='accepted'