首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从一个与Server中的另一个表完全匹配的表中选择所有记录?

如何从一个与Server中的另一个表完全匹配的表中选择所有记录?
EN

Stack Overflow用户
提问于 2018-01-26 10:17:36
回答 2查看 297关注 0票数 1

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

代码语言:javascript
运行
复制
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匹配并计数intable @2)

场景1:

代码语言:javascript
运行
复制
insert into @one values (195),(84)

我只需要得到ID- 15,因为所有的都是匹配的,表@one中的记录计数是2。

Scenario2:

代码语言:javascript
运行
复制
Insert into @one values (195),(84),(8)

我只需要得到ID- 16和17,17:因为所有的服务都在匹配,表@1中的记录计数是3,16:因为两个服务是匹配的,表@1中的记录计数是3,NULL的意思是“不管是谁”。

你有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-26 11:01:57

恐怕你接受的答案是错误的(正如你在评论中所注意到的)。下面是工作查询:

代码语言:javascript
运行
复制
-- 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
票数 0
EN

Stack Overflow用户

发布于 2018-01-26 10:30:44

代码语言:javascript
运行
复制
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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48459389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档