I’m using the MySQL classicmodels database. The following query works fine (note the where clause)
select
customers.customerNumber as 'Customer ID',
customers.customerName as 'Customer Name',
count(orders.orderNumber) as 'Total Orders Placed'
from customers
left join orders on customers.customerNumber = orders.customerNumber
where customers.customerNumber > 200
group by
customers.customerNumber
order by
3 asc
But the following results in an error. The intention is to display only those customers in the resulting set of rows, who have placed more than 3 orders. What am I doing wrong?
select
customers.customerNumber as 'Customer ID',
customers.customerName as 'Customer Name',
count(orders.orderNumber) as 'Total Orders Placed'
from customers
left join orders on customers.customerNumber = orders.customerNumber
where count(orders.orderNumber) > 3
group by
customers.customerNumber
order by
3 asc
MySQL error is: Error Code: 1111. Invalid use of group function
Aggregate functions (
COUNT(), AVG(), SUM(),etc) cannot appear in theWHEREclause, owing to when they are calculated. Instead, they belong in aHAVINGclause: