SQL
Lab
Amazon Medium Ranking Classic

Top Customers
By
Spending

Find the top customer or customers who spent the most money.

Table Schema

Inspect
Table

interactive
ColumnTypeDescription
order_idintegerOrder identifier.
customer_idintegerCustomer identifier.
order_datedateDate of the order.
ColumnTypeDescription
order_idintegerOrder identifier.
product_idintegerProduct identifier.
quantityintegerUnits bought.
priceintegerPrice per unit.

Sample Data

Input
Output

Sample Input: orders
order_idcustomer_idorder_date
11012024-01-01
21022024-01-02
31012024-01-03
Sample Input: order_items
order_idproduct_idquantityprice
1102100
2201200
3101100
Expected Output
customer_idtotal_spent
101300

SQL Editor

Run
Query

postgresql
Waiting for query

customer_idtotal_spent
101300

Hints

Unlock
Clues

Hint 01: Join orders to order_items on order_id.
Hint 02: Multiply quantity by price before summing.
Hint 03: Rank customers by total spent and keep the top one or tied tops.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH customer_spending AS (
  SELECT
    o.customer_id,
    SUM(oi.quantity * oi.price) AS total_spent
  FROM orders AS o
  JOIN order_items AS oi
    ON o.order_id = oi.order_id
  GROUP BY o.customer_id
),
ranked_customers AS (
  SELECT
    customer_id,
    total_spent,
    DENSE_RANK() OVER (ORDER BY total_spent DESC) AS spend_rank
  FROM customer_spending
)
SELECT
  customer_id,
  total_spent
FROM ranked_customers
WHERE spend_rank = 1
ORDER BY customer_id;

Explanation

Step By
Step

01

Join orders with order items and calculate each order's value.

02

Sum those values by customer to get total spending.

03

Keep every customer tied for the highest total spent.

Related Questions

Keep
Solving