SQL
Calculating Total Order Value Per Customer
Learn to join multiple tables (customers, orders, order_items, products) and use aggregate functions like SUM to calculate total spending per customer.
SELECT
c.customer_id,
c.customer_name,
SUM(oi.quantity * p.price) AS total_spent
FROM
customers c
INNER JOIN
orders o ON c.customer_id = o.customer_id
INNER JOIN
order_items oi ON o.order_id = oi.order_id
INNER JOIN
products p ON oi.product_id = p.product_id
GROUP BY
c.customer_id, c.customer_name
ORDER BY
total_spent DESC;
How it works: This query joins `customers`, `orders`, `order_items`, and `products` tables to link customer information with their order details and product prices. It then uses `SUM` to calculate the total amount spent by each customer, grouping the results by `customer_id` and `customer_name` and ordering them by `total_spent` in descending order. This is fundamental for understanding customer value.