I'm trying to write an SQL query that displays customers' names who have a total purchase greater than the average purchase of all purchases.
I tried using the code below, but it gives an error.
SELECT C.FirstName
FROM CUSTOMERS as C
JOIN ORDERS AS O ON C.CustomerID = O.CustomerID
GROUP BY O.CustomerID
HAVING O.TotalPaid < Avg(O.TotalPaid);
And here's the error:
Error Code: 1054. Unknown column 'O.TotalPaid' in 'having clause'
It seems that you are having three errors:
O.TotalPaid
into a SUM
because the HAVING
should contain aggregated data.>
because you are looking for values greater than the average.Query should be like this:
SELECT C.FirstName
FROM CUSTOMERS as C
JOIN ORDERS AS O ON C.CustomerID = O.CustomerID
GROUP BY O.CustomerID
HAVING SUM(O.TotalPaid) > (SELECT AVG(TotalPaid) FROM ORDERS);
Another possible option should be including into the SELECT
the SUM(O.TotalPaid)
like this:
SELECT C.FirstName, SUM(O.TotalPaid)
FROM CUSTOMERS as C
JOIN ORDERS AS O ON C.CustomerID = O.CustomerID
GROUP BY O.CustomerID
HAVING SUM(O.TotalPaid) > (SELECT AVG(TotalPaid) FROM ORDERS);