2016-12-30 63 views
-1

我有一個表food,有兩列:fruitspecies。每個物種可以有多個行,具有不同的值fruit。我想找到所有正好吃到1 fruit的物種,並且知道這些物種的價值fruitHAVING查詢中的多個術語

這個查詢工作發現,只吃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 
           ^

感謝您的幫助!

+0

請不要比較數字與字符串。 '1'是一個數字''1''是一個字符串值,而不是數字 –

+0

它不一定是'有count(fruit)= 1'嗎? – melpomene

+0

@a_horse_with_no_name在SQL或至少PostgreSQL TBH中,這很好,''''是一個未知類型的文字。例如,它實際上是_correct_方法來指定一個'NUMERIC'文字。我個人更喜歡明確寫出'NUMERIC'1'',但'1'也可以,類型是從操作符和其他參數中推斷出來的。如果您使用綁定參數,那麼會發生這種情況,除非您在協議消息中明確指定了其類型。 –

回答

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的最大值只是返回該元素。

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 ;