Sql Find Sets With Common Members (relational Division)
I have separate sets of 'classes' and 'groups', each of which has been assigned one or more tags. I would like to find, for each group, the subset of classes that contains the same
Solution 1:
I think this should also work
selectdistinct g.GroupID, c.ClassID
from@Groups g
leftjoin@Classes c on g.TagID = c.TagID
wherenotexists (
select*from@Groups g2
where g2.GroupID = g.GroupID
and g2.TagID notin (
select TagID
from@Classes c2
where c2.ClassID = c.ClassID
)
) or c.ClassID isnullSolution 2:
You can join the tables together, and demand that all tags from the group are found in the class:
select g.GroupID
, c.ClassID
from@Groups g
join@Classes c
on c.TagID = g.TagID
groupby
g.GroupID
, c.ClassID
havingcount(c.TagID) =
(
selectcount(*)
from@Groups g2
where g2.GroupID = g.GroupID
)
This does not list groups without a matching class, and I can't think of a simple way to do so.
Post a Comment for "Sql Find Sets With Common Members (relational Division)"