HAVING查询中的多个术语

时间:2016-12-30 22:34:46

标签: sql postgresql

我有一个包含两列的表foodfruitspecies。每个物种可以有多行,具有不同的fruit值。我想找到所有正好吃1 fruit的物种,并知道这些物种fruit的价值。

此查询用于查找只吃1种fruit的物种:

select species
from food
group by species
having count(species) = '1'

现在我想要2列,一列species,另一列是关联的fruit。如何在having参数中查询多个术语?我试过了:

select species, fruit
from food
group by species
having count(species) = '1'

但是得到以下错误:

ERROR:  column "food.fruit" must appear in the
GROUP BY clause or be used in an aggregate function
LINE 1: select species, fruit
                                   ^

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

试试这个

   select species, fruit
    from food
    where species in (select species
                      from food
                      group by species
                      having count(species) = 1)

答案 1 :(得分:0)

这有点像黑客攻击,但我相信以下内容会起作用:

select species, max(fruit)
from food
group by species
having count(fruit) = 1

这样我们选择"最大值"每个物种的果实(按字母顺序排列)。但是选择一组大小为1的最大值只会返回该元素。

答案 2 :(得分:0)

你需要有一个聚合函数才能得到你的成果(因为你没有按fruit分组)。当你正在寻找一种水果时,你可以使用聚合函数min(或max,这没关系),并得到你想要的。这是一个例子:

WITH food(fruit, species) AS
(
    VALUES 
    ('apple', 'apple eater 1'),
    ('apple', 'apple eater 2'),
    ('orange', 'only orange eater'),
    ('pear', 'only pear eater'),
    ('melon', 'lots of fruits eater'),
    ('watermelon', 'lots of fruits eater'),
    ('strawberry', 'lots of fruits eater'),
    ('strawberry', 'berry eater'),
    ('blueberry', 'berry eater')
)

SELECT
    species, min(fruit) AS fruit
FROM
    food
GROUP BY 
    species
HAVING
    count(species)=1
ORDER BY
    species ;