This sql code throws an
aggregate functions are not allowed in WHERE
SELECT o.ID , count(p.CAT) FROM Orders o INNER JOIN Products p ON o.P_ID = p.P_ID WHERE count(p.CAT) > 3 GROUP BY o.ID;
How can I avoid this error?
Aggregate functions work on sets of data. A WHERE clause doesn't have access to entire set, but only to the row that it is currently working on.
An aggregate function can be used in a WHERE clause only if that clause is part of a subquery of a HAVING clause and the column name specified in the expression is a correlated reference to a group. If the expression includes more than one column name, each column name must be a correlated reference to the same group.
Aggregate functions can be used in both the SELECT and HAVING clauses (the HAVING clause is covered later in this chapter). Aggregate functions cannot be used in a WHERE clause.
You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for. You can use a sub-query which contains an aggregate in the WHERE clause.
Replace WHERE
clause with HAVING
, like this:
SELECT o.ID , count(p.CAT) FROM Orders o INNER JOIN Products p ON o.P_ID = p.P_ID GROUP BY o.ID HAVING count(p.CAT) > 3;
HAVING
is similar to WHERE
, that is both are used to filter the resulting records but HAVING
is used to filter on aggregated data (when GROUP BY
is used).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With