I have three tables:
User -- contains users
Group -- contains a set of groups that users can be members of
Membership -- Contains PKs from User and Group to indicate that User is a member of group
The PKs are UserId, GroupId, and MembershipId respectively, and Membership has FKs to the other two tables.
This is pretty standard stuff, the one tweak is that a user can be a member of multiple groups, and groups have a level (1, 2, 3, 4). The user’s current group is the group they are a member of that has the highest level.
Now I want to get a count of the number of members in each group. At the moment I have something like this:
SELECT Count(*) FROM Membership
FROM Membership M1
INNER JOIN Group G1 ON M1.GroupId = G1.GroupId
INNER JOIN User ON User.UserId = M1.UserId
WHERE
M1.GroupId = @groupId
AND NOT EXISTS (
SELECT * FROM Membership M2
INNER JOIN Group G2 ON M2.GroupId = G2.GroupId
WHERE M2.UserId = M1.UserId
AND G1.Priority < G2.Priority)
So for each user I am looking to see if there is another membership in a group with a higher priority. This is obviously pretty horrible, especially when you have a lot of rows, but I am at a little bit of a loss on how to improve it.
Ideally, I’d like to transform it so that I get the counts for all Groups rather than just one select (as above.)
Any ideas how to do this more efficiently?
Which RDBMS? this will work in SQL Server…