PROSQL 45: Complex SQL Questions Solution
Suparna Chowdhury
Data Scientist | Python, SQL, and Tableau Expert | Driving Data Insights
DAY 4: PROSQL45 CHALLENGE (19 NOVEMBER, 2024)
A big thanks to Ankit Bansal the year-end challenge! I’m taking it on by solving 2 complex SQL questions every day from a playlist of 79 problems.
?PROBLEM 7:
This problem is sourced from Leetcode.com : https://leetcode.com/problems/trips-and-users/
Problem: Calculate Daily Cancellation Rate for Unbanned Users
You are given two tables: Trips and Users. A trip can be canceled by either the client or the driver. The goal is to compute the cancellation rate for each day between 2013-10-01 and 2013-10-03, considering only trips involving unbanned clients and drivers.
The cancellation rate is defined as the ratio of canceled trips (either by the client or driver) to the total number of trips, rounded to two decimal places.
Requirements:
Output:
Return the cancellation rate for each day within the specified date range.
Video Solution by Ankit: https://www.youtube.com/watch?v=EjzhMv0E_FE&list=PLBTZqjSKn0IeKBQDjLmzisazhqQy4iGkb&index=8
Step-by-Step Solution Approach:
SELECT request_at AS Day,
ROUND(SUM(CASE WHEN status <> 'completed' THEN 1 ELSE 0 END)* 1.0/ COUNT(*),2) AS 'Cancellation Rate'
FROM Trips t
INNER JOIN Users c
ON t.client_id = c.users_id
INNER JOIN Users d
ON t.driver_id = d.users_id
WHERE t.request_at BETWEEN '2013-10-01' AND '2013-10-03'
AND c.banned <> 'Yes' AND d.banned <> 'Yes'
GROUP BY request_at
ORDER BY request_at;
PROBLEM 8:
This problem is sourced from Leetcode.com: https://leetcode.ca/all/1194.html
Problem: Find the Winner in Each Group
You are given two tables: Players and Matches. In each match, two players from the same group compete. The winner in each group is the player with the highest total score across all matches in that group. In case of a tie, the player with the lower player_id wins.
Write an SQL query to find the winner of each group.
?Video Solution: https://www.youtube.com/watch?v=SfzbR69LquU&list=PLBTZqjSKn0IeKBQDjLmzisazhqQy4iGkb&index=6
Step-by-Step Solution Approach:?
WITH scores AS (
SELECT first_player AS player_id
, first_score AS score
FROM matches
UNION ALL
SELECT second_player AS player_id
, second_score AS score
FROM matches), final_score AS (
SELECT s.player_id, p.group_id, SUM(score) AS total_score,
rank() over(partition by p.group_id order by SUM(score) desc,s.player_id) as rn
FROM scores s
INNER JOIN players p
ON p.player_id = s.player_id
GROUP BY s.player_id, p.group_id)
SELECT group_id , player_id as winner
FROM final_score
where rn = 1;
Let’s level up our SQL skills!
Join me on this journey as I tackle more challenges each day. Let’s improve our SQL skills together before the year ends!
Check out the full solutions on Github here!