← Questions
Customer order totals and latest order amount (SQL)
0
I was asked this
No reports yet. Sign in to say where you were asked it.
You have tables of customers, their orders and returned orders. Write one query that returns a row for every customer, including those with no orders, with their order count, total amount spent, the date of their most recent order and that order's amount.
Interface
Unless you agree on a different interface with the interviewer, assume these tables:
customers(customer_id, customer_name)orders(order_id, customer_id, order_date, amount)-
returns(order_id, return_date)— an order appears here if it was returned.
Return customer_id, customer_name, total_orders, total_amount, latest_order_date and latest_order_amount, one row per customer. Count every order for now; returns come up as a follow-up.
Example
customers: (1, Ada), (2, Ben), (3, Cy)
orders: (10, 1, 2025-01-05, 40), (11, 1, 2025-02-10, 25), (12, 2, 2025-01-20, 90)
customer_id customer_name total_orders total_amount latest_order_date latest_order_amount
1 Ada 2 65 2025-02-10 25
2 Ben 1 90 2025-01-20 90
3 Cy 0 0 NULL NULL
Constraints
- A customer can have many orders, several on the same date.
- Joining
returnsmust not double-count orders.
Clarifying questions
- When a customer has two orders on their latest date, which amount is the latest one?
- Should a customer with no orders show
0orNULLfor totals? - Do returned orders count toward the totals?
What a strong answer covers
- Aggregate
ordersper customer in one CTE, and pick the latest order per customer in another withROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC). -
LEFT JOINboth fromcustomersso customers without orders stay, withCOALESCEfor zero counts and amounts. - A stated tie rule for the latest order, made deterministic in the window's
ORDER BY. - Why joining
orderstoreturnsbefore aggregating can inflate sums, and how to avoid it.
Follow-ups
- Exclude returned orders from the totals and from the latest order (
NOT EXISTSagainstreturns). - Return every order on the latest date when there is a tie.
- Add each customer's average order value and days since their latest order.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
