Medium SQL Challenge: Using MIN() and MAX()

365 Days of Daily Coding: Day 29

I had a good start in the morning today. I posted in my instagram today. It’s called @karmarambles where I share daily doses of positivity, motivation and stories to keep you going. At first, when I started it, I only wanted to fill up my time but as I work on it, I find immense pleasure knowing that and hoping that they might help someone.

Today’s sqlpad challenge: Given a table called “payment”, I had to find the maximum amount and the minimum amount that was spent by the customers. Each customer are identified with a unique id called customer_id and they could have made many different purchases throughout the month. Therefore, first hint was to find the aggregated amount that was spent in a month per customer.

Table: payment

col_namecol_type
payment_idinteger
customer_idsmallint
staff_idsmallint
rental_idinteger
amountnumeric
payment_tstimestamp with time zone
“payment” table

Expected Output:

max_spendmin_spend
153.623
Expected output

My Solution:

SELECT MIN(spend) AS min_spend, MAX(spend) AS max_spend
FROM(
SELECT SUM(amount) AS spend
FROM payment
WHERE EXTRACT(MONTH FROM payment_ts) = 06
GROUP BY customer_id) AS subq;

Leave a comment