Skip to content
Advertisement

How to select MAX from AVG?

I’m practicing for my SQL exam and I can’t figure out the following question:

“Of the average amount paid per customer, show the highest amount.”

So to retrieve the average amount paid, I would do the following:

SELECT AVG(Amount) AS 'Average amount paid'
FROM Payment;

Then I would like to retrieve the highest average amount out of this list of averages. I thought the following would do the trick:

SELECT MAX(AVG(Amount)) AS 'Highest average amount paid'
FROM Payment;

This doesn’t seem to work. I get the following error:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

I would like some help with this. What is the correct way to approach this? Thank you in advance.

Advertisement

Answer

In SQL Server, you can order the records and use TOP 1 to keep only the record that has the highest amount:

SELECT TOP 1 Customer_id, AVG(Amount) AS [Average amount paid]
FROM Payment
GROUP BY customer_id
ORDER BY [Average amount paid] DESC;

Note: for this query to make sense, you need a GROUP BY clause. Without it, it would just return one record, with the average of payments within the whole table.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement