SQL Challenge: Using Windows Functions RANK()

365 Days of Daily Coding: Day 40

It’s going to be almost 1 year since I have been working from home this coming Feb. As many of you, I struggled with adjusting WFH practice because I did not have a proper office set up. I was using a portable table and a duvet as my table and chair which were giving me some back aches.

After 1 year, I would say I have pretty much adjusted to WFH and I have also done a good job of setting up a proper routine for myself. I cook often but not always. It’s become rather very easy to order food online these days because of the pandemic. It’s amazing how quickly we adjust to our environment.

Today, I completed 1 easy and 1 medium challenge. These challenges are becoming pretty redundant as a couple of challenges I solved previouly are rather similar.

Easy Challenge 1:

SELECT title FROM(
SELECT f.title, RANK() OVER (ORDER BY COUNT(a.actor_id) DESC) AS rnk
FROM film f LEFT JOIN film_actor a
ON f.film_id = a.film_id
GROUP BY f.film_id) AS k
WHERE rnk = 2;

Medium Challenge 1:

SELECT first_name, last_name FROM
(SELECT c.first_name, c.last_name, RANK() OVER(ORDER BY SUM(p.amount) DESC) AS rnk
FROM customer c LEFT JOIN payment p
ON c.customer_id= p.customer_id
WHERE EXTRACT(YEAR FROM p.payment_ts) = 2020 AND EXTRACT(MONTH FROM p.payment_ts)=05
GROUP BY c.customer_id) AS k
WHERE rnk = 2;

Leave a comment