sqlhaving

Problem with customer name display involving average


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'


Solution

  • It seems that you are having three errors:

    1. You should include the O.TotalPaid into a SUM because the HAVING should contain aggregated data.
    2. You should do a subquery for the average value to keep it constant.
    3. It should be > 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);