Medium SQL Day: Using JOINS

365 Days of Daily Coding: Day 69

Today was a lazy day. I slept a lot throughout the day. Prev, I used to feel a lot guilty when I did not do anything productive. Nowadays, my stance has changed. I feel like I work so hard throughout the week and I deserve the rest on the weekends. The hustle hard after 9-5 is kinda toxic. When you see everybody doing it, the FOMO kicks in. I would love the extra money but not at the expense of me missing the joy of living life.

I solved 2 medium SQL challenge that I was unable to solve before. Therefore, I am extremely happy. I am exhilirated with my coding journey so far reflecting back to the Day 1 when I started. I felt so small when I was not able to solve a challenge. I have also started reading up documentation on Python. I have read few people in reddits recommending to read the documentation to truly understand the nature of the language. The goal is not to memorise all the functions that is available but to get the feel of the language.

Medium SQL Challenge 1:

WITH temp AS (
  SELECT * FROM rental
  WHERE EXTRACT(YEAR FROM DATE(rental_ts)) = 2020 AND
  EXTRACT(MONTH FROM DATE(rental_ts)) = 05
  )

SELECT COUNT(demand_category)
FROM(
SELECT CASE 
WHEN counts <=1 THEN 'not-in-demand'
ELSE 'in-demand'
END AS demand_category
FROM (
SELECT film_id, COUNT(rental_id) AS counts
FROM(
SELECT f.film_id, k.rental_id FROM film f LEFT JOIN
(SELECT i.film_id, i.inventory_id, t.rental_id						
FROM inventory i LEFT JOIN temp t
ON i.inventory_id = t.inventory_id
WHERE t.rental_id IS NOT NULL
ORDER BY i.film_id, i.inventory_id)k
ON f.film_id = k.film_id) AS l
GROUP BY film_id
) AS m) AS n GROUP BY demand_category;

Medium SQL Challenge 2:

WITH temp AS(
SELECT *
  FROM rental r 
  WHERE EXTRACT(YEAR FROM DATE(r.rental_ts)) = 2020
  AND EXTRACT(MONTH FROM DATE(r.rental_ts)) = 06
)
SELECT f.film_id, f.title
FROM film f JOIN (
SELECT i.film_id, COUNT(t.rental_id) AS counts 
from inventory i JOIN temp t
ON i.inventory_id = t.inventory_id
GROUP BY i.film_id
ORDER BY counts DESC
LIMIT 5) k
ON f.film_id = k.film_id;

Leave a comment