Find out what group id contains all relevant attributes in SQL

后端 未结 1 624
悲哀的现实
悲哀的现实 2021-01-25 09:41

So lets say in this case, the group that we have is groups of animals.

Lets say I have the following tables:

animal_id | attribute_id | animal
---------         


        
相关标签:
1条回答
  • 2021-01-25 10:08

    You can use group by and having:

    with a as (
          select 1 as attribute_id from dual union all
          select 4 as attribute_id from dual
         )
    select t.animal_id, t.animal
    from t join
         a
         on t.attribute_id = a.attribute_id
    group by t.animal_id, t.animal
    having count(*) = (select count(*) from a);
    

    The above will find all animals that have those attributes and any others. If you want animals that have exactly those 2 attributes:

    with a as (
          select 1 as attribute_id from dual union all
          select 4 as attribute_id from dual
         )
    select t.animal_id, t.animal
    from t left join
         a
         on t.attribute_id = a.attribute_id
    group by t.animal_id, t.animal
    having count(*) = (select count(*) from a) and
           count(*) = count(a.attribute_id);
    
    0 讨论(0)
提交回复
热议问题