如何 select 来自一个 table 的所有记录与 SQL 服务器中的另一个 table 完全匹配?

How to select all records from one table that exactly match another table in SQL Server?

我有一个关于 select 的棘手问题:我有这个 table 结构:

declare @one as table (serviceid int null)

declare @two as table (id int null, serviceid int null)

insert into @two 
values (15,195),(15,84),(16,195),(16,84),(16,NULL),(17,195),(17,84),(17,8)

我需要得到完全匹配的 @two.ID(匹配 serviceid 并计入table @two )

场景一:

insert into @one values (195),(84)

我只需要获取 ID- 15,因为所有 serviceid 都匹配并且 table @one 中的记录数是 2.

场景2:

Insert into @one values (195),(84),(8)

我只需要获取 ID- 16 和 17,17:因为所有 serviceid 都匹配并且 table@one 中的记录数是 3.,16 :因为两个服务匹配,记录计数在 table @one 是 3 和 NULL 意味着'无关紧要'(谁)

你有什么想法吗?

declare @one as table (serviceid int null)

declare @two as table (id int null, serviceid int null)

insert into @two values (15,195),(15,84),(16,195),(16,84),(16,NULL),(17,195),(17,84),(17,8);
--insert into @one values (195),(84);
Insert into @one values (195),(84),(8)

select distinct t.id
from @two t
where exists (select * from @one o where t.serviceid = o.serviceid)
      and (select count(*) from @one) = (select count(*) from @two t1 where t1.id = t.id);

恐怕您接受的答案是错误的(正如您在评论中注意到的那样)。这是工作查询:

-- tables declaration ---------------------------------------------------------------------
declare @one as table (serviceid int null)
declare @two as table (id int null, serviceid int null)
-- values insert --------------------------------------------------------------------------
insert into @two values (15,195),(15,84),(16,195),(16,84),(16,NULL),(17,195),(17,84),(17,8)
insert into @one values (195),(84)
-- actual query ---------------------------------------------------------------------------
select id from (
select id,
       --check, where we have null records in @one caused by null values in @two, which is acceptable (assifgned value when acceptable = 0)
       case when ([ONE].serviceid is not null and [TWO].serviceid is not null) or ([ONE].serviceid is null and [TWO].serviceid is null) then 0 else 1 end [IsMatched]
from (
    select *, COUNT(*) over (partition by id) as [idCount] from @two
) [TWO] left join (
    select serviceid, COUNT(*) over (partition by (select null)) [idCount] from @one
) [ONE] on ([TWO].idCount = [ONE].idCount and [TWO].serviceid = [ONE].serviceid)
) [a] group by id
having SUM(IsMatched) = 0