Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using group by on two fields and count in SQL

Tags:

sql

mysql

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?

like image 982
Marc Avatar asked Apr 30 '12 09:04

Marc


People also ask

Can we use GROUP BY and count together in SQL?

We can use GROUP BY to group together rows that have the same value in the Animal column, while using COUNT() to find out how many ID's we have in each group. It returns a table with three rows (one for each distinct animal).

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Can you GROUP BY 2 columns in SQL?

We can group the resultset in SQL on multiple column values. When we define the grouping criteria on more than one column, all the records having the same value for the columns defined in the group by clause are collectively represented using a single record in the query output.


2 Answers

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

like image 117
Corbin Avatar answered Sep 22 '22 11:09

Corbin


SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup 
like image 23
user1127214 Avatar answered Sep 20 '22 11:09

user1127214