2015-12-17 116 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