Skip to content Skip to sidebar Skip to footer

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

select distinct g.GroupID, c.ClassID
from @Groups g
    left join @Classes c on g.TagID = c.TagID
where not exists (
    select *
    from @Groups g2
    where g2.GroupID = g.GroupID
        and g2.TagID not in (
            select TagID
            from @Classes c2
            where c2.ClassID = c.ClassID
        )
    ) or c.ClassID is null

Solution 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
group by
        g.GroupID
,       c.ClassID
having  count(c.TagID) =
        (
        select  count(*)
        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.

Example at SQL Fiddle.


Post a Comment for "SQL Find Sets With Common Members (relational Division)"