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_name | col_type |
|---|---|
| payment_id | integer |
| customer_id | smallint |
| staff_id | smallint |
| rental_id | integer |
| amount | numeric |
| payment_ts | timestamp with time zone |
Expected Output:
| max_spend | min_spend |
|---|---|
| 153.6 | 23 |
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