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

标签 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

最佳答案

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

关于sql - 如何选择属于一个组而不是另一个组的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63495686/

相关文章:

android - 从 Android 应用程序共享 SQLite 数据库,无需中间副本

mysql - 同时获取每列中每个值的计数

php - CodeIgniter 中表 A 中的位置但不是 B 中的位置

mysql - 测验应用程序的数据库设计

mysql - 一张表中的复杂 SQL 查询

mysql - 使用用户定义的变量指定列别名

c# - Xamarin SQLite PCL 实现

c++ - 为什么将 strlen 重新实现为循环+减法?

hadoop - pig 脚本: count returns 0 on null field

mysql - 如何选择评论数、投票总数以及活跃用户是否投票