简体   繁体   English

计算 DISTINCT 值的出现次数

[英]Count the occurrences of DISTINCT values

I am trying to find a MySQL query that will find DISTINCT values in a particular field, count the number of occurrences of that value and then order the results by the count.我试图找到一个 MySQL 查询,它将在特定字段中找到 DISTINCT 值,计算该值的出现次数,然后按计数对结果进行排序。

example db示例数据库

id         name
-----      ------
1          Mark
2          Mike
3          Paul
4          Mike
5          Mike
6          John
7          Mark

expected result预期结果

name       count
-----      -----
Mike       3
Mark       2
Paul       1
John       1
SELECT name,COUNT(*) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

What about something like this:这样的事情怎么样:

SELECT
  name,
  count(*) AS num
FROM
  your_table
GROUP BY
  name
ORDER BY
  count(*)
  DESC

You are selecting the name and the number of times it appears, but grouping by name so each name is selected only once.您正在选择名称及其出现的次数,但按名称分组,因此每个名称仅被选择一次。

Finally, you order by the number of times in DESCending order, to have the most frequently appearing users come first.最后,您按照 DESCending 顺序按次数排序,以使出现频率最高的用户排在第一位。

Just changed Amber's COUNT(*) to COUNT(1) for the better performance.只是将 Amber 的 COUNT(*) 更改为 COUNT(1) 以获得更好的性能。

SELECT name, COUNT(1) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

I am trying to find a MySQL query that will find DISTINCT values in a particular field, count the number of occurrences of that value and then order the results by the count.我正在尝试找到一个MySQL查询,该查询将在特定字段中找到DISTINCT值,计算该值的出现次数,然后按计数顺序对结果进行排序。

example db示例数据库

id         name
-----      ------
1          Mark
2          Mike
3          Paul
4          Mike
5          Mike
6          John
7          Mark

expected result预期结果

name       count
-----      -----
Mike       3
Mark       2
Paul       1
John       1

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

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