So I created an solution for the Challenge: Each Country’s Best Customer of Building and Organizing Complex Queries, but my solution was quite different from the suggested solution and I’m wondering why and how I can take a lesson from this.
Challenge to be found on: https://app.dataquest.io/m/465/building-and-organizing-complex-queries/8/challenge-each-countrys-best-customer
The suggested solution is as follows:
WITH
customer_country_purchases AS
(
SELECT
i.customer_id,
c.country,
SUM(i.total) total_purchases
FROM invoice i
INNER JOIN customer c ON i.customer_id = c.customer_id
GROUP BY 1, 2
),
country_max_purchase AS
(
SELECT
country,
MAX(total_purchases) max_purchase
FROM customer_country_purchases
GROUP BY 1
),
country_best_customer AS
(
SELECT
cmp.country,
cmp.max_purchase,
(
SELECT ccp.customer_id
FROM customer_country_purchases ccp
WHERE ccp.country = cmp.country AND cmp.max_purchase = ccp.total_purchases
) customer_id
FROM country_max_purchase cmp
)
SELECT
cbc.country country,
c.first_name || " " || c.last_name customer_name,
cbc.max_purchase total_purchased
FROM customer c
INNER JOIN country_best_customer cbc ON cbc.customer_id = c.customer_id
ORDER BY 1 ASC
My solution is like this:
WITH
customer_purchase_amount AS
(
SELECT
customer_id,
SUM(total) total_purchased
FROM invoice
GROUP BY 1
),
best_customer_country AS
(
SELECT
customer_id,
first_name || " " || last_name customer_name,
country
FROM customer
)
SELECT
bcc.country,
bcc.customer_name,
MAX(cpa.total_purchased) total_purchased
FROM best_customer_country bcc
INNER JOIN customer_purchase_amount cpa ON cpa.customer_id = bcc.customer_id
GROUP BY 1
ORDER BY 1 ASC;
All feedback is welcome. Thanks!