Skip to content
Advertisement

Sql query to return information about customers which has spent the most amount

I have a database about the shop, and I need to return full information of the first 5 customers, which has spent the most amount, and in returned results also display that total amount. (counting all his/her payments together from the payments table). Order descending by the total amount. Can someone help with the query for this?

Customers Table enter image description here

Payments Table enter image description here

Advertisement

Answer

It should be something like this. You might have to play around but it will give you a good start.

SELECT c.CustomerName, SUM(p.amount) AS Total
FROM CustomersTable c
INNER JOIN PaymentsTable p
ON c.customerNumber = p.customerNumber
GROUP BY p.customerNumber DESC LIMIT 5
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement