Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Group By & Count Multiple Fields

Tags:

sql

php

mysql

If I have a single field, say, project_id where I want to count the occurrences, I would do something like:

select project_id, count(project_id) as count from tbl group by project_id, order by count desc

What if I want to count the occurrences of a combination of two fields in the same table, i.e. count the number of rows where the combination of project_id and service_id are unique?

So, so I have records in my table like:

project_id   service_id
1            1
1            2
1            2
1            2
1            2
1            3
1            4
1            4
1            4


I would want the result of my query to be something like:

project_id   service_id   count
1            1            1
1            2            4
1            3            1
1            4            3
like image 475
David Avatar asked Jan 28 '26 17:01

David


1 Answers

select project_id, service_id, count(*) as count 
from tbl group by project_id, service_id
order by count(*) desc

Just add service_id to your group by and select list. That should do it.

EDIT -

As per comment from @Rajah it seems that for your expected output, you need to use

order by project_id asc, service_id asc
like image 166
Sachin Shanbhag Avatar answered Jan 31 '26 07:01

Sachin Shanbhag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!