如何 select 属于一组但不属于另一组的项目
How to select items which belong to one group but not another
Sqlite3
我如何 select 只是宠物而不是食物的动物? 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;
Sqlite3
我如何 select 只是宠物而不是食物的动物? 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;