119

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?

1
  • 3
    i wanted another case, count of sugroups for each group so this is the query SELECT a, b, COUNT(distinct b) FROM tbl GROUP BY a Commented May 18, 2019 at 12:58

4 Answers 4

179

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

Sign up to request clarification or add additional context in comments.

5 Comments

Hello Corbinb. Thank you very much. it is working. I did what you are suggesting but insted of group by a, b I did group by a and b. Thanks again
a and b looks like a statement to MySQL (not actually sure if it would be a syntax error or if it would group on the 0 or 1 return -- I would assume a syntax error, especially for varchar fields). To group on multiple columns, you just use a comma.
Thanks a lot!! .. The issue with me was I wasn't able to phrase my question and spent a lot of time googling finally landed here for a simple and dot solution.
Instead of the count I needed the entire record details. For example, grpA has to 2 subgroups: subA and subB, so I need to retrieve the entire record for each of the subgroups. Can anyone please help me. @Corbin
i wanted count of sugroups for each group so this is the query SELECT a, b, COUNT(distinct b) FROM tbl GROUP BY a
11
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

1 Comment

Instead of the count I needed the entire record details. For example, grpA has to 2 subgroups: subA and subB, so I need to retrieve the entire record for each of the subgroups. Can anyone please help me. @user1127214
8

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

2 Comments

Seems a typo to me group!= groupName
Instead of the count I needed the entire record details. For example, grpA has to 2 subgroups: subA and subB, so I need to retrieve the entire record for each of the subgroups. Can anyone please help me. @farzane
0

It is easily possible. You need to GROUP BY multi fields. Those are on 'mainGroup' and then 'subGroup'

select mainGroup, subGroup, Count(mainGroup) from table group by mainGroup, subGroup

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.