如何选择属于一个组而不属于另一个组的项目

时间:2020-08-19 22:17:28

标签: sql sqlite count subquery relational-division

Sqlite3

如何选择仅是宠物而不是食物的动物? POF是“宠物或食物”列。动物可以属于这两个群体。这是实际问题的较小版本。我不想将其拆分为更多表。

animal  pof
----------
fish    pet
fish    food
pig     food
cat     pet
dog     pet
horse   pet
mouse   pet
duck    pet
duck    food
cow     food
rabbit  pet
rabbit  food
gerbil  pet
worm    <null>
chicken food

我有以下内容,但似乎很尴尬:

SELECT * from 
(SELECT  NAME, POF, count(*) as cnt
 FROM    ANIMALS
 GROUP BY NAME) AS GC
 WHERE GC.cnt == 1 AND GC.POF == 'pet'

正确屈服:

NAME    POF cnt
---------------
cat     pet  1
dog     pet  1
gerbil  pet  1
horse   pet  1
mouse   pet  1

3 个答案:

答案 0 :(得分:1)

一种方法使用聚合:

select animal, count(*) cnt
from animals
group by animal
having min(pof) = max(pof) an min(pof) = 'pet'

如果没有重复项(如数据中所示),则计数始终为1 ...,并且您可以使用not exists来产生相同的结果(取决于您的数据,或可能没有,效率更高):

select animal
from animals a
where 
    pof = 'pet' 
    and not exists (select 1 from animals a1 where a1.animal = a.animal and a1.pof <> 'pet')

答案 1 :(得分:1)

使用NOT IN排除所有具有pof = 'food'的动物:

select *
from animals
where pof = 'pet'
and animal not in (select animal from animals where pof = 'food')

或者,如果只需要列animal,则可以使用EXCEPT

select animal from animals where pof = 'pet'
except
select animal from animals where pof = 'food'

请参见demo

答案 2 :(得分:0)

使用聚合的另一种方法

select animal
from animals
group by animal
having avg(case when pof='pet' then 1 else 0 end)=1;
相关问题