关于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)我需要得到完全匹配的@two.ID (与serviceid匹配并计数intable @2)
场景1:
insert into @one values (195),(84)我只需要得到ID- 15,因为所有的都是匹配的,表@one中的记录计数是2。
Scenario2:
Insert into @one values (195),(84),(8)我只需要得到ID- 16和17,17:因为所有的服务都在匹配,表@1中的记录计数是3,16:因为两个服务是匹配的,表@1中的记录计数是3,NULL的意思是“不管是谁”。
你有什么想法吗?
发布于 2018-01-26 11:01:57
恐怕你接受的答案是错误的(正如你在评论中所注意到的)。下面是工作查询:
-- 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发布于 2018-01-26 10:30:44
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);https://stackoverflow.com/questions/48459389
复制相似问题