sqlbeginner10 minutes

Find the Top 3 Customers by Total Purchase Amount

Write an SQL query to identify the top 3 customers who have spent the most in total purchases, using a sample sales database.

Challenge prompt

Given a table named 'Sales' with columns 'CustomerID', 'OrderID', and 'Amount', write an SQL query to return the top 3 customers ranked by their total purchase amount in descending order. The result should include 'CustomerID' and 'TotalSpent'.

Guidance

  • Aggregate the sales amounts by CustomerID using a GROUP BY clause.
  • Use the SUM() function to calculate total amount spent per customer.
  • Order your results by the total spent in descending order.
  • Limit the output to only the top 3 customers.

Hints

  • Try using GROUP BY CustomerID and SUM(Amount).
  • Use ORDER BY with DESC to sort from highest to lowest total spent.
  • LIMIT 3 will give you only the top 3 results.

Starter code

SELECT CustomerID, SUM(Amount) as TotalSpent
FROM Sales
-- Your code here

Expected output

CustomerID | TotalSpent -----------|----------- 101 | 4500 203 | 3800 150 | 3200

Core concepts

GROUP BYSUM()ORDER BYLIMIT

Challenge a Friend

Send this duel to someone else and see if they can solve it.