Sql 如何找到相等的子集?

Sql 如何找到相等的子集?,sql,sql-server,tsql,relational-division,Sql,Sql Server,Tsql,Relational Division,我有一个包含子集的表。如何找到与给定id具有相同子集的读卡器id?例如: 输入读取器=4 预期输出:读取器1和5 子集大小并不总是=3,因为在示例中它可以是动态的。什么是正确的SQL查询 declare @t table( reader int not null, book int, pages int ) insert into @t (reader, book, pages) select 1, 1, 100 union select 1, 2, 201 union sel

我有一个包含子集的表。如何找到与给定id具有相同子集的读卡器id?例如:

输入读取器=4 预期输出:读取器1和5

子集大小并不总是=3,因为在示例中它可以是动态的。什么是正确的SQL查询

declare @t table(
   reader int not null,
   book int,
   pages int
)
insert into @t (reader, book, pages)
select 1, 1, 100 union
select 1, 2, 201 union
select 1, 3, 301 union
select 2, 1, 100 union
select 2, 3, 101 union
select 2, 3, 301 union
select 3, 1, 100 union
select 3, 2, 101 union
select 3, 3, 301 union
select 4, 1, 100 union
select 4, 2, 201 union
select 4, 3, 301 union
select 5, 1, 100 union
select 5, 2, 201 union
select 5, 3, 301

select * from @t

这有点痛苦,但您可以使用自连接:

with t as (
      select t.*, count(*) over (partition by reader) as cnt
      from @t t
     )
select t.reader
from t left join
     t t2
     on t2.book = t.book and
        t2.pages = t.pages and
        t2.cnt = t.cnt and
        t2.reader = 4
group by t.reader, t.cnt
having count(*) = t.cnt and
       count(*) = count(t2.reader);

需要使用
左连接
,以避免子集关系。也就是说,拥有“4”的所有书籍以及其他书籍。

这是处理关系划分的通用方法。它检查集合x是否包含集合y中的所有元素(可能更多):


您没有任何名为
id
的列,也没有具有唯一值的列可以推断它是id。此外,到目前为止您尝试了什么,为什么不起作用?我不知道应该是什么查询。
with reqd as (
    select book, pages
    from @t
    where reader = 1
)
select t.reader
from @t as t
inner join reqd on t.book = reqd.book and t.pages = reqd.pages
group by t.reader
having count(reqd.book) = (select count(*) from reqd)