MySQL:Group By&计算多个字段

时间:2011-03-16 17:10:00

标签: php mysql sql

如果我有一个字段,比如project_id,我想要计算出现次数,我会做类似的事情:

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

如果我想计算同一个表中两个字段组合的出现次数,即计算project_id和service_id组合唯一的行数,该怎么办?

所以,我的表中记录如下:

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

1 个答案:

答案 0 :(得分:9)

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

只需将service_id添加到您的group byselect列表中即可。应该这样做。

编辑 -

根据@Rajah的评论,您的预期输出似乎需要使用

order by project_id asc, service_id asc