2017-01-16 145 views
0

我有這個SQL來計算組,但是我想說count在哪裏大於1,任何人都可以幫忙,因爲它目前不工作?SQL group by count其中count大於

select Code, Qty, Count(Qty) from Product where ItemName = 'Banana' 
and Count(Qty) > 1 
Group by Code, Qty order by 3 desc 
+0

你知道你的'Qty'意味着組? – Mureinik

+0

可能重複的[SQL - 有VS在哪裏](http://stackoverflow.com/questions/9253244/sql-having-vs-where) – Aquillo

回答

2

你應該把這個情況在HAVING -clause:

select Code, Qty, Count(Qty) Qty 
from Product 
where ItemName = 'Banana' 
Group by Code 
having count(Qty) > 1 
order by 3 desc 

HAVING,同時WHERE之前評估GROUP BY後評估,這意味着WHERE -clauses將在recordlevel過濾而HAVING -clauses過濾器關於總量。

對於更詳細的解釋,檢查SQL - having VS where

我也建議你閱讀Logical Processing Order of the SELECT statement

+4

沒有看到你在我之前回答。由於我們的答案几乎相同,所以我刪除了我的並向上提出了你的答案。 –

+0

@Jeffrey我沒有回答你的問題'group by count'的解決方案,因爲我不完全明白你想要達到的目標。如果這個答案沒有完全導致你想要的集合,你能否包含一個數據的例子和預期的輸出? – Aquillo