如何解决如何选择属于一个组而不属于另一个组的项目
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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。