MySQL 在两个字段上使用 group by 并在 SQL 中计数

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

Using group by on two fields and count in SQL

mysqlsql

提问by Marc

I have a table in my mysql db that has two columns: group and subgroup. See below.

我的 mysql 数据库中有一个表,它有两列:组和子组。见下文。

 group, subGroup
 grp-A, sub-A
 grp-A, sub-A
 grp-A, sub-B      
 grp-B, sub-A
 grp-B, sub-B
 grp-B, sub-B

I am trying to get the number of records for each unique couple group/subGroup.

我正在尝试获取每个唯一夫妇组/子组的记录数。

This is what I expect:

这是我的期望:

group, subGroup, count
grp-A, sub-A, 2
grp-A, sub-B, 1
grp-B, sub-A, 1
grp-B, sub-B, 2

After reading some posts I tried several sql queries using group by, count(), but I do not manage to get the expected result. How can I fix this?

在阅读了一些帖子后,我尝试了使用 group by、count() 的几个 sql 查询,但我没有得到预期的结果。我怎样才能解决这个问题?

回答by Corbin

I think you're looking for: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b

我认为您正在寻找: SELECT a, b, COUNT(a) FROM tbl GROUP BY a, b

回答by farzane

You must group both columns, group and sub-group, then use the aggregate function COUNT().

您必须对列、组和子组进行分组,然后使用聚合函数COUNT()

SELECT
  group, subgroup, COUNT(*)
FROM
  groups
GROUP BY
  group, subgroup

回答by user1127214

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup