Easy SQL Challenge: Using COUNT() With DISTINCT()

365 Days of Coding: Day 26

In my opinion, out of the three challenge sites I have tried, leetcode and sqlpad comes close to close. The only difference between them being that leetcode offers challenges for multiple languages and has an active user base that frequently shares their insights in the forums. Since, I have finished most of the challenges in leetcode except for a medium challenge, I am going to continue using sqlpad for now.

Todays’s challenge was to find out the unique counts of customers per year and month.

Table: rental

col_namecol_type
rental_idinteger
rental_tstimestamp with timezone
invetory_idinteger
customer_idsmallint
return_tstimestamp with timezone
staff_idsmallint
last_updatetimestamp with timezone
Table “rental”

Expected Solution:

yearmonuu_cnt
20201123
20202456
20203789
Expected Solution

My Solution:

SELECT EXTRACT(YEAR FROM rental_ts) AS year, 
EXTRACT(MONTH FROM rental_ts) AS mon, COUNT(DISTINCT customer_id) AS uu_cnt
FROM rental
GROUP BY year, mon;

Leave a comment