Using group by on two fields and count in SQL

MysqlSql

Mysql Problem Overview


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

 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?

Mysql Solutions


Solution 1 - Mysql

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

Solution 2 - Mysql

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

Solution 3 - Mysql

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcView Question on Stackoverflow
Solution 1 - MysqlCorbinView Answer on Stackoverflow
Solution 2 - Mysqluser1127214View Answer on Stackoverflow
Solution 3 - MysqlfarzaneView Answer on Stackoverflow