简体   繁体   English

如何按2列计算记录数

[英]How to calculate count of records by 2 columns

In MySQL I have a table. MySQL我有一张表。

Example: 例:

id name type
1 Thomas 2
2 Thomas 2
3 Thomas 1
4   Paul 3
5   Paul 4
6   Paul 4

I need calculate same records by 2 columns. 我需要按2列计算相同的记录。 Result for this example should be: 此示例的结果应为:

name   type   countOfRecords
Thomas 2       2
Thomas 1       1
Paul   3       1
Paul   4       2

Could you help me with this request? 您能帮我这个要求吗?

Since you want records in your result set for each name and type <name,type> pair you need to group by name and type . 由于要在结果集中记录每个名称并键入<name,type>对,因此需要按nametype进行分组。

SELECT 
name,
type,
COUNT(*) countOfRecords
FROM your_table
GROUP BY name,type;

Note: 注意:

Group BY <some column> would generate a result set where number of rows = number of distinct / different / unique <some column> . Group BY <some column>将生成一个结果集,其中行数=唯一/不同/唯一<some column>

Same holds for multiple columns in GROUP BY clause. GROUP BY子句中的多个列也是如此。

This may be right solution: 这可能是正确的解决方案:

SELECT  name, type, COUNT(*) as countOfRecords
FROM your_table
GROUP BY name,type;

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

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