Due to the syntax of mySQL this statement is not allowed (a counted element cannot be used within the WHERE part):
Illegal syntax:
SELECT COUNT(x) AS amount ... WHERE amount > 0
But how do I handle a COUNTed element via WHERE ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
edit
Note that your original query may not do what you think it does. You probably want
WHERE x > 0instead:This is because
HAVING amount > 0is essentially meaningless if there are ANY x values greater than 0. MySQL will automatically group and include all of your rows, counting every one of them. It looks like you want to know the number of rows with a non-zero amount in x, so you need to specify with WHERE that only those rows should match the original criteria to be counted. See below for an example case of needing an aggregate function with HAVING.original answer:
You do this with
HAVING. The syntax is exactly the same asWHERE, but it is evaluated after the aggregation.The difference is important, since it allows you to limit which rows are counted with WHERE, and then limit the rows returned with HAVING.
For instance, let’s say I wanted to know how much money I made per department on sales of LESS THAN $10, only if it made more than $1000: