7

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
2
  • Are you sure you meant to group by Qty? Commented Jan 16, 2017 at 11:14
  • Possible duplicate of SQL - having VS where Commented Jan 16, 2017 at 11:19

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

2 Comments

Didn't see you answered before me. Since our answers are pretty much the same, I've deleted mine and upvoted yours.
Then we have 2 columns that have same name Qty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.