如果我有一个字段,比如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
答案 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 by
和select
列表中即可。应该这样做。
编辑 -
根据@Rajah
的评论,您的预期输出似乎需要使用
order by project_id asc, service_id asc