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

时间:2022-02-11 12:28:17

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

我的mysql db中有一个表,它有两列:group和subgroup。见下文。

 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查询,但是我没有得到预期的结果。我该怎么解决这个问题呢?

3 个解决方案

#1


113  

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

我想你在寻找:从tbl组中选择a, b, COUNT(a) BY a, b

#2


6  

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

#3


6  

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

#1


113  

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

我想你在寻找:从tbl组中选择a, b, COUNT(a) BY a, b

#2


6  

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

#3


6  

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