每个组的用户数

时间:2014-06-18 08:28:57

标签: mysql sql join group-by

我需要生成一个结果集,为所有userGroup提供每组中的用户数:

insert into groupUser value(1,"administrator");
insert into groupUser value(2,"commercial");
insert into groupUser value(3,"development");

insert into user value(1,"jack", 3);
insert into user value(2,"bill", 1);
insert into user value(3,"mark", 3);

结果应该是:

administrator : 1
commercial : 0
development : 2

我找不到解决方案。

2 个答案:

答案 0 :(得分:1)

因为您没有发布表格模式...

select g.Name, count(u.usergroupId) as members
from groupUser g left join user u 
on  u.usergroupId = g.id
group by g.Name

Demo Here

答案 1 :(得分:0)

我认为这会给你更好的结果

Select GroupUser,[Count]

from   (Select groupid,count(*) 'Count' from user group by groupid) t

join    Groupuser G

on      G.id = t.id