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

问题描述

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

解决方法

一种方法使用聚合:

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')
,

使用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

,

使用聚合的另一种方法

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...