Medium SQL Challenge: Using SUM(), COUNT() and DISTINCT() To Find The Average Value

365 Days of Daily Coding: Day 27

I am quite not feeling well today. I think I might have a stiff neck. I am planning to see a acupuncturist that my friend has been seeing for a while. The clinic is called Xing Lin Tcm Centre. I hope there isn’t much issue with my body. I am kinda nervous.

Today, I solved a medium challenge questions which is becoming relatively easy. It’s either that or the questions are comparatively easier compared to the challenges in leetcode or hackerrank.

Given a table called “payment”, I had to find out the average amount customer spent per year and month.

Table: payment

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

Expected Output:

yearmonavg_spend
20201143.56
202022345.9
Sample of the expected output

My solution:

SELECT EXTRACT(YEAR FROM payment_ts) "year", EXTRACT(MONTH FROM payment_ts) mon,
SUM(amount)/COUNT(DISTINCT customer_id) avg_spend
FROM payment
GROUP BY year, mon;

Leave a comment