SQL group by count where count大于

时间:2017-01-16 11:11:38

标签: sql tsql

我有这个计算组的SQL,但我想说计数大于1的位置,任何人都可以帮助,因为它目前不起作用吗?

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

1 个答案:

答案 0 :(得分:3)

你应该把这个条件放在HAVING - 子句中:

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

HAVINGGROUP BY之后进行评估,而之前评估WHERE,这意味着WHERE - 子句将在记录级别上进行过滤,而HAVING - 子句会对聚合进行过滤

有关更详细的说明,请查看SQL - having VS where

我还建议您阅读Logical Processing Order of the SELECT statement

相关问题