[英]How to select all records from one table that exactly match another table in SQL Server?
I have a tricky question about select: I have this table structure: 我有一个关于select的棘手问题:我有这个表结构:
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)
I need get exactly matching @two.ID (that matches the serviceid and count intable @two ) 我需要得到完全匹配的@ two.ID (匹配serviceid并计数不稳定的@two)
Scenario 1: 方案1:
insert into @one values (195),(84)
I need get only ID- 15 , because all serviceid is matching and record count in table @one is 2. 我只需要获取ID- 15 ,因为所有serviceid都匹配,并且表@one中的记录计数为2。
Scenario2: 方案2:
Insert into @one values (195),(84),(8)
I need get only ID- 16 and 17, 17 : because all serviceid is matching and record count in table @one is 3. , 16 : because two services are matching,record count in table @one is 3 and NULL
means 'Don't Matter'(whoever) 我需要得到的只是ID- 16和17,17:因为所有的服务ID是匹配和表@One记录数为3,16:因为两个服务匹配,在表@One记录数为3种, NULL
手段“唐” t事项”(无论如何)
Do you have any idea? 你有什么主意吗?
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);
I am afraid, that the answer you accepted is wrong (as you noticed in comment). 恐怕,您接受的答案是错误的(正如您在评论中注意到的那样)。 Here is working query: 这是工作查询:
-- 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.