简体   繁体   English

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

[英]calculate the count and then sum of total count MySql

My Query 我的查询

$sql = 'SELECT status FROM tablename';

And the result 结果

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

Now i can find the total count of each status 现在我可以找到每个状态的总数

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

This will give 这将给


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

How do i sum only completed and accepted count? 我如何只completed和已accepted计数?

This is called conditional summing, when you place the condition within the sum() function: 将条件放在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

Or you can use where to filter the subquery first: 或者,您可以使用where首先过滤子查询:

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

Its simple, replace group by by where 其操作简单,取代group bywhere

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

从tname中选择COUNT(状态)AS cnt status =“已完成”或status =“已接受”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM