计算值出现在 MySQL 中特定列的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10199950/
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 13:00:01  来源:igfitidea点击:

Count number of times value appears in particular column in MySQL

mysqlaggregate-functions

提问by Mahmoud Al-Qudsi

This has probably been asked before, but I'm unable to make my way through the myriad of search results.

之前可能有人问过这个问题,但我无法通过无数的搜索结果。

Given a non-normalized MySQL table, what is the most optimized query to count the number of times each distinct value of column x was used?

给定一个非规范化的 MySQL 表,计算列 x 的每个不同值的次数的最优化查询是什么?

e.g. Given a table containing

例如,给定一个包含

mike
mary
mike

Return results like:

返回结果如:

mike 2
mary 1

From the MySQL documentation, it would seem that countis an aggregate function that can be used with GROUP BY, but it's not doing what I want (it's returning the total number of rows in the GROUP BY, not the number of appearances for each row. i.e. this does not work SELECT count(email) as c FROM orders GROUP BY email

从 MySQL 文档来看,这似乎count是一个可以与 一起使用的聚合函数GROUP BY,但它没有做我想要的(它返回 中的总行数GROUP BY,而不是每行的出现次数。即这不是工作SELECT count(email) as c FROM orders GROUP BY email

回答by Nesim Razon

select email, count(*) as c FROM orders GROUP BY email

回答by garnertb

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name

回答by Erwald

Take a look at the Group by function.

查看按功能分组。

What the group by function does is pretuty much grouping the similar value for a given field. You can then show the number of number of time that this value was groupped using the COUNT function.

group by 函数所做的几乎是对给定字段的相似值进行分组。然后,您可以使用 COUNT 函数显示该值分组的次数。

MySQL Documentation

MySQL 文档

You can also use the group by function with a good number of other function define by MySQL (see the above link).

您还可以将 group by 函数与 MySQL 定义的许多其他函数一起使用(请参阅上面的链接)。

mysql> SELECT student_name, AVG(test_score)
    ->        FROM student
    ->        GROUP BY student_name;

回答by davethecoder

select name, count(*) from table group by name;

i think should do it

我认为应该这样做