Skip to content
Advertisement

Query that will result in a list of customer names and the average order value made by each customer

I have a database and I need to create a query that will retrieve a list of customer names and the average order value made by each customer. I tried:

This is my database structure: database structure enter image description here

But I get an error, what can be wrong?

Advertisement

Answer

But I get an error, what can be wrong ?

You are trying to use an aggregate function Count within an aggregate function and getting a MISUSE OF AN AGGREGATE FUNCTION.

i.e. – > misuse of aggregate function COUNT()

Additionally you are not GROUP‘ing your results and thus will receive the entire average rather than a per-customer average.

  • Aggregate functions work on a GROUP the default being all unless a GROUP BY clause places the rows into GROUPS.

You could instead of AVG(COUNT(o.order_id)*f.price) use sum(f.price) / count(*). However, there is an average aggregate function avg. So avg(f.price)’ is simpler.

Additionally as you want an average per customer you want to use a GROUP BY c.customer clause.

Thus you could use :-

This would result in something like :-

enter image description here

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