Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

sql server - 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 (or more) tags for each group.

Some sample data:

declare @Groups table
(
    GroupID int,
    TagID int
)

insert @Groups
values (1,1),(1,2),(1,3),
    (2,1),(2,2),
    (3,1),(3,2),(3,3),(3,4)

declare @Classes table
(
    ClassID int,
    TagID int
)

insert @Classes
values (1,1),(1,2),
    (2,1),(2,2),
    (3,1),(3,2),(3,3)

select * from @Groups
select * from @Classes

And output:

GroupID TagID
1       1
1       2
1       3
2       1
2       2
3       1
3       2
3       3
3       4

ClassID TagID
1       1
1       2
2       1
2       2
3       1
3       2
3       3

An example result set would look like this:

declare @Results table
(
    GroupID int,
    ClassID int
)

insert @Results
values (1,3),(2,1),(2,2),(2,3),(3,null)

select * from @Results

Results output:

GroupID ClassID
1       3
2       1
2       2
2       3
3       NULL

I understand this is a relational division type problem, involving having and count. These posts describe what I want to do, but I can't figure out how to apply the examples to the particular case above:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...