简体   繁体   中英

MySQL: Group By & Count Multiple Fields

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, ie 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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM