Mysql get count users in group

Mark :

I have a question which I cant really work out. I have 1 table with 2 2 columns, userid and groupid

entries:

  • user1: group1
  • user1: group2
  • user1: group3
  • user2: group1
  • user2: group2
  • user3: group1

Now I want to make a Sql query that which gives the following data:

there are 3 people that are a member of 1 group

there are 2 people that are a member of 2 groups

there is 1 person that is a member of 3 groups.

The Impaler :

You need to precompute the counts, and then a simple aggregation will do:

select c, count(*)
from (
  select count(distinct g) as c from t group by u
) x 
group by c

Assumes the table is t, with columns u and g.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=402211&siteId=1