2017-08-03 93 views
2

我目前工作的一个存储过程,我需要编写一个查询,它选择所有GroupId s表示没有所有TypeIds查找组匹配条件列表不完全

关于这个例子:

Id | GroupId | TypeId | 
---+---------+--------+ 
1 | 1  | 1  | 
2 | 1  | 2  | 
3 | 1  | 3  | 
4 | 2  | 1  | 
5 | 2  | 2  | 
6 | 3  | 1  | 
7 | 3  | 2  | 
8 | 3  | 3  | 
9 | 4  | 2  | 

我想选择GroupId第2和第4,因为那些groupes不具备这三个TypeId的1,2和3 GroupId 4只TypeId 2而GroupId 2只TypeId的1和2

我当前的查询看起来是这样,但不工作:

SELECT [A].ActorPoolId 
FROM [OfferCatalog].[Actor] [A] 
WHERE [A].ActorTypeId IN ('1', '2', '3') 

你知道如何解决这个问题吗?

回答

4

可以用户group by + having组合:

select [A].ActorPoolId 
from [OfferCatalog].[Actor] [A] 
where [A].ActorTypeId in ('1', '2', '3') 
group by [A].ActorPoolId 
having count(distinct [A].ActorTypeId) < 3 

可以省略的情况下,使用ActorTypeIddistinct每个ActorPoolId唯一的。

+1

谢谢,完美的作品! :) – TimHorton