2017-04-10 69 views
0

我想編寫一個查詢返回小鎮,並從每個小鎮選手的數量大於5爲什麼不能在where子句中使用Count()運算符?我如何解決這個問題?

我的查詢選手的數量現在看起來是這樣的:

select hometown, count(hometown) from marathon2016 where count(hometown) > 5 group by hometown order by count(hometown) desc;

但sqlite3的這一回應:

Error: misuse of aggregate: count()

什麼我做錯了什麼,爲什麼不能我使用COUNT()在這裏,我就改用什麼。

回答

0

嘗試以下操作:

select 
    hometown, 
    count(hometown) as hometown_count 
from 
    marathon2016 
group by 
    hometown 
having 
    hometown_count > 5 
order by 
    hometown_count desc; 
+0

那麼,有沒有辦法只能獲得其中只有5人以上的城鎮中列出的結果? –

+0

@BryceEdwards我誤解了你的問題。更新了我的答案。 –

1

當你試圖在WHERE原因使用聚合函數(如count),你通常是尋找,而不是爲HAVING WHERE:

select hometown, count(hometown) 
from marathon2016 
group by hometown 
having count(*) > 5 
order by count(*) desc 

你不能在WHERE原因使用聚合,因爲聚集在多個行計算(由GROUP BY指定)但如果是用於過濾各行,以確定哪些行集GROUP BY將被應用到(即WHERE在分組之前發生並在分組後應用聚合)。

+0

真棒,謝謝!如果 –

+0

@BryceEdwards這個答案幫助你,你需要通過點擊投票按鈕下方的複選標記接受它。這樣其他訪問者可以很容易地看到你如何解決你的問題。謝謝! –

相關問題