SQL find sets with common members (relational division)

梦想的初衷 提交于 2019-11-29 14:57:22

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!