Question

What is the total amount each customer spent at the restaurant?

Solution

SELECT customer_id, '$' || SUM(price) as total_amount_spent
FROM sales
INNER JOIN menu on sales.product_id = menu.product_id
GROUP BY customer_id;
customer_idtotal_amount_spent
B$74
C$36
A$76

Walkthrough

Let’s start by asking who has visited our restaurant so far?

SELECT DISTINCT(customer_id) 
FROM sales;
customer_id
B
C
A

Okay, what kinda purchases were made by A ?

SELECT *
FROM sales 
WHERE customer_id = 'A';
customer_idorder_dateproduct_id
A2021-01-011
A2021-01-012
A2021-01-072
A2021-01-103
A2021-01-113
A2021-01-113

Nice. Can we get the prices for these products next to their sale records?

SELECT *
FROM sales
INNER JOIN menu ON sales.product_id = menu.product_id
WHERE customer_id = 'A';
customer_idorder_dateproduct_idproduct_idproduct_nameprice
A2021-01-0111sushi10
A2021-01-0722curry15
A2021-01-0122curry15
A2021-01-1133ramen12
A2021-01-1133ramen12
A2021-01-1033ramen12

Okay, so the total amount that customer A spent must be the sum of all these prices. There’s a SUM aggregator we could use here.

SELECT SUM(price)
FROM sales
INNER JOIN menu ON sales.product_id = menu.product_id
WHERE customer_id = 'A';
sum
76

Can we perform this summation for every customer and store it as one row per customer. Yup, GROUP BY comes to the rescue.

SELECT customer_id, SUM(price)
FROM sales
INNER JOIN menu ON sales.product_id = menu.product_id
GROUP BY customer_id;
customer_idsum
B74
C36
A76

Excellent, we got the data we need. Maybe polish it slightly by prefixing the numbers with a $ and naming the column to something better?

SELECT customer_id, '$' || SUM(price) as total_amount_spent
FROM sales
INNER JOIN menu on sales.product_id = menu.product_id
GROUP BY customer_id;
customer_idtotal_amount_spent
B$74
C$36
A$76