2015-12-17 48 views
3

我有以下相關字段的表:雙條件計數選擇,而分組

entity_id | grouping_id | type_id 
--------------------------------- 
1   | 1   | 1 
2   | 1   | 1 
3   | 1   | 2 
4   | 2   | 1 
5   | 2   | 2 

我想選擇所有grouping_id值,其中有型的n X的數量和類型M Y號。什麼,我最初以爲例如將工作:

select grouping_id from t_entities 
group by grouping_id, type_id 
having 
    count(case type_id when 1 then 1 else null end) = 2 
and 
    count(case type_id when 2 then 1 else null end) = 1 

理論上返回有1型和2型的1 2所有grouping_id值,但由於該條款是由TYPE_ID分組及,我得不到任何回報,因爲每個組都獨立存在,但是如果我通過type_id刪除組,則會出現聚合錯誤。有沒有辦法做到這一點,而不使用臨時表的原始查詢?

回答

1

您的詢問處於正確的軌道,但不是按照type_id分組,您應該按grouping_id分組。按type_id進行分組,您永遠不會得到具有兩個不同值的東西,因此having中的and子句將不起作用。您應該能夠執行以下返回grouping_id =1作爲結果:

select grouping_id 
from t_entities 
group by grouping_id 
having count(case type_id when 1 then 1 else null end) = 2 
    and count(case type_id when 2 then 1 else null end) = 1; 

SQL Fiddle with Demo