6

I have this SQL that counts the groups, but I want to say where the count is greater than 1, can anyone help as it doesn't currently work?

select Code, Qty, Count(Qty) from Product where ItemName = 'Banana'
and Count(Qty) > 1
Group by Code, Qty order by 3 desc
Jeffrey
  • 2,095
  • 3
  • 20
  • 36

1 Answers1

16

You should put this condition in the 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 is evaluated after GROUP BY while WHERE is evaluated before, meaning that WHERE-clauses will filter on recordlevel while HAVING-clauses filter on aggregates.

For a more detailed explanation, check SQL - having VS where

I would also recommend you to read Logical Processing Order of the SELECT statement

Community
  • 1
  • 1
Menno
  • 12,175
  • 14
  • 56
  • 88