简体   繁体   English

MySQL:计算每行不同值的出现次数

[英]MySQL: Count occurrences of distinct values for each row

Based on an example already given, I would like to ask my further question.基于已经给出的例子,我想问我进一步的问题。 MySQL: Count occurrences of distinct values MySQL:计算不同值的出现次数

example db示例数据库

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

expected result预期结果

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

In my opinion 'GROUP BY' doesn't help.在我看来,'GROUP BY' 没有帮助。 Thank you very much.非常感谢。

Simplest approach would be using Count() as Window Function over a partition of name ;最简单的方法是在name的分区上使用Count()作为窗口函数 but they are available only in MySQL 8.0.2 and onwards .但它们仅在MySQL 8.0.2 及更高版本中可用。

However, another approach is possible using a Derived Table .但是,使用派生表的另一种方法是可能的。 In a sub-select query (Derived Table), we will identify the counts for each unique name .在子选择查询(派生表)中,我们将识别每个唯一name的计数。 Now, we simply need to join this to the main table, to show counts against each name (while not doing a grouping on them):现在,我们只需要将其加入主表,以显示每个名称的计数(同时不对它们进行分组):

SELECT 
  t1.name, 
  dt.total_count 
FROM your_table AS t1 
JOIN 
(
 SELECT name, 
        COUNT(*) AS total_count 
 FROM your_table
 GROUP BY name
) AS dt ON dt.name = t1.name 
ORDER BY t1.id 

If MySQL 8.0.2+ is available, the solution would be less verbose:如果 MySQL 8.0.2+ 可用,解决方案将不那么冗长:

SELECT 
  name, 
  COUNT(*) OVER (PARTITION BY name) AS total_count 
FROM your_table

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

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