I get the solution and my answer was somewhat similar, however mine was different in a few ways and I had questions on it. I’ll post my code and the solution code below.
So my curiosity/question stems from:
- When I query the “invoice” table separately, I see the “total” column is the sum of purchases for ALL invoices
- Because of knowledge of #1, it didn’t seem to appear that I need to aggregate “I.TOTAL” because it already is.
- So because of this I did a COUNT(*) because we’re GROUP BY at the customer level (all invoice_line and invoice_ids should roll into it) > the total purchases look correct
- But of course the issue is with the I.TOTAL because I assumed two things 1) it is already the sum of sums of all purchases by “CUSTOMER_ID” and 2) even without, we still GROUP BY customer name.
Questions:
Basically, just curious why it is TOTAL column is sum of sums in INVOICE table, but without sum() the results in our query is the sum of only ONE arbitrary invoice (after the join)?
Also, does the GROUP BY not apply to everything in select statement (if so, I’d imagine it would group the I.TOTAL by all purchases?
My code:
SELECT
c.first_name || " " || c.last_name customer_name,
COUNT(*) number_of_purchases,
i.total total_spent,
CASE
WHEN i.total < 40 THEN “small spender”
WHEN i.total > 100 THEN “big spender”
ELSE “regular”
END
AS customer_category
FROM customer c
INNER JOIN invoice i ON c.customer_id = i.customer_id
GROUP BY customer_name
ORDER BY customer_name
Solution:
SELECT
c.first_name || " " || c.last_name customer_name,
COUNT(i.invoice_id) number_of_purchases,
SUM(i.total) total_spent,
CASE
WHEN SUM(i.total) < 40 THEN “small spender”
WHEN SUM(i.total) > 100 THEN “big spender”
ELSE “regular”
END
AS customer_category
FROM customer c
INNER JOIN invoice i ON c.customer_id = i.customer_id
GROUP BY customer_name
ORDER BY customer_name