2017-08-03 95 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