SQL query returns duplicate rows when joining three tables with GROUP BY
10:50 10 Sep 2026

I'm trying to get a summary of customer orders that includes the total number of orders and the total amount spent, but my query is returning duplicate rows and inflated totals instead of one row per customer.

customers (customer_id, name, email)

orders (order_id, customer_id, order_date)

order_items (item_id, order_id, product_id, quantity, price)

SELECT 
    c.customer_id,
    c.name,
    COUNT(o.order_id) AS total_orders,
    SUM(oi.quantity * oi.price) AS total_spent
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
GROUP BY c.customer_id, c.name;
join group-by aggregate-functions