【问题标题】:How to select items which belong to one group but not another如何选择属于一个组但不属于另一个组的项目
【发布时间】:2020-12-09 05:40:06
【问题描述】:

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

【问题讨论】:

    标签: sql sqlite count subquery relational-division


    【解决方案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')
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        另一种使用聚合的方式

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-18
          相关资源
          最近更新 更多