PROSQL 45: Complex SQL Questions Solution
Suparna Chowdhury
Data Scientist | Python, SQL, and Tableau Expert | Driving Data Insights
DAY 2: PROSQL45 CHALLENGE (17 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 3: Scenario based question:
Challenge Inspiration: Watch the Solution Video
?You have a table names entries that records information about user visits. The table contains the following columns:
Write a SQL query to find the following information for each user: the total number of visits, the floor the user visited the most, and a comma-separated list of distinct resources used by the user across all visits.
Step by Step Solution Approach:
SQL Code:
WITH total_visited AS (
SELECT name, COUNT(1) AS total_visited
FROM entries
GROUP BY name
),
most_visited AS (
SELECT name,
floor,
COUNT(1) AS floor_visits,
RANK() OVER (PARTITION BY name ORDER BY COUNT(1) DESC) AS rn
FROM entries
GROUP BY name, floor
),
resources AS (
SELECT DISTINCT name, resources
FROM entries
),
used_resources AS (
SELECT name, STRING_AGG(resources, ', ') AS resources
FROM resources
GROUP BY name
)
SELECT mv.name,
tv.total_visited,
mv.floor AS most_visited_floor,
ur.resources AS resources
FROM total_visited tv
INNER JOIN most_visited mv ON tv.name = mv.name
INNER JOIN used_resources ur ON tv.name = ur.name
WHERE mv.rn = 1;
OUTPUT:
PROBLEM 4: SQL Question Asked in a FAANG Interview:
Challenge Inspiration: Watch the Challenge Video
Problem: Write a query to find the date for the Nth occurrence of Sunday in the future from a given date.
?
Step by Step Solution Approach:
1 + 7 * @N - DATEPART(WEEKDAY, @input_date)
This expression computes how many days to add to the input date to reach the Nth Sunday.
SQL Code:
DECLARE @input_date DATE
DECLARE @N INT
SET @N = 2
SET @input_date = '2024-11-15'
SELECT DATEADD(DAY, 1 + 7*@N - DATEPART(WEEKDAY, @input_date), @input_date) AS nth_sunday;
Output:
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!