MySQL 查询 - 使用 COUNT 的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6709747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:29:27  来源:igfitidea点击:

MySQL query - using SUM of COUNT

mysql

提问by David Ryder

This query:

这个查询:

SELECT COUNT(source) AS count
FROM call_details
GROUP BY source
HAVING count >1

Returns about 1500 (the number I'm looking for) results with only the count field. How could I also return the sum of all count fields? When I try

仅使用计数字段返回大约 1500 个(我正在寻找的数字)结果。我怎样才能返回所有计数字段的总和?当我尝试

SELECT COUNT(source) AS count,
SUM(count) as total
FROM call_details
GROUP BY source
HAVING count >1

I get an 'Unknown column 'count' in 'field list' error.

我在“字段列表”错误中收到“未知列“计数”。

And

SELECT COUNT(source) AS count,
SUM(COUNT(source)) as total
FROM call_details
GROUP BY source
HAVING count >1

gives me an 'Invalid use of group function'

给我一个“无效使用组功能”

Any ideas? I can do a mysql_num_rows($result)of the first set (to get the info I need) but I really want to do it through MySQL.

有任何想法吗?我可以做mysql_num_rows($result)第一组(以获取我需要的信息),但我真的很想通过 MySQL 来做。

回答by Paul

SELECT COUNT(count) FROM (SELECT COUNT(source) AS count
FROM call_details
GROUP BY source
HAVING count > 1) as A

回答by Marc B

You can't get a global total in a row-context. At the time the the COUNT() completes on any particular row, there's nothing to SUM, because the other rows haven't been calculated yet.

您无法在行上下文中获得全局总数。当 COUNT() 在任何特定行上完成时,SUM 没有任何内容,因为其他行尚未计算。

You'd have to run the SUM query first to get your individual stats, then sum manually in your script, or re-run the query with a surrounding SUM clause:

您必须首先运行 SUM 查询以获取您的个人统计信息,然后在脚本中手动求和,或者使用周围的 SUM 子句重新运行查询:

SELECT SUM(count) FROM (
   SELECT original query here...
)

回答by Rahul

Try this

尝试这个

select mycount, sum(mycount) as sumcount
from
(SELECT COUNT(source) AS mycount FROM call_details GROUP BY source HAVING mycount >1)   counttable 

回答by sagi

Assuming you are going to fetch all the results in the application anyway, I think the most efficient way would be to just sum it up in the application code.

假设您无论如何都要获取应用程序中的所有结果,我认为最有效的方法是将其汇总到应用程序代码中。

回答by user3162020

Just simply remove the 'Group by' clause in the select query that counts

只需简单地删除计数的选择查询中的“分组依据”子句

# first, get your counts by source
SELECT COUNT(source) AS count
FROM call_details
GROUP BY source
HAVING count >1

# then, get the overall total
SELECT COUNT(source) AS count
FROM call_details
HAVING count >1