β¨ Programming
Medium
SQL Joins
Average Order Value Per Customer
Question
Calculate each customer's average order value. Return full name, number of orders, and average order amount. Only include customers with at least 2 orders.
Use customers and orders tables.
Solution
SELECT
c.first_name || ' ' || c.last_name AS customer_name,
COUNT(o.order_id) AS order_count,
ROUND(AVG(o.total_amount), 2) AS avg_order_value
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(o.order_id) >= 2
ORDER BY avg_order_value DESC;
Explanation: JOIN and GROUP BY customer. AVG computes average order total. HAVING filters to customers with at least 2 orders.