SQL Challenge: Case Study. Step-by-step walkthrough of a SQL... | by Chloe Lubin | Towards Data Science

In a previous post, I talked about how to use a framework to solve a SQL challenge. Today, I’m going to do a walkthrough of this challenge, asked by Microsoft in February 2021. Before you continue reading this article, I highly encourage you to try solving this question on your own. The more you practice solving SQL questions, the better you’ll get at them. Alright, let’s get into it!
The question asks us to:
select the most popular client_id based on a count of the number of users who have at least 50% of their events from the following list: ‘video call received’, ‘video call sent’, ‘voice call received’, ‘voice call sent’.
Before I start working on this question, I like to visualize how the information appears in the dataset. Let’s run a simple SELECT statement to check the data stored in the table fact_events.
SELECT *FROM fact_eventsLIMIT 10
The query returns the following output:
Out of curiosity, I wonder if all the values in the list provided appear in the dataset:
SELECT     event_typeFROM fact_eventsWHERE event_type IN ('video call received',                    'video call sent', 'voice call received',                    'voice call sent')GROUP BY event_type
It looks like only 2 of the 4 values are included. Even though the 2 other values don’t appear in the current dataset, they may appear later as data gets appended to the table. You can’t assume that the data will remain static. As a result, let’s keep all 4 values in our filter.
Great! I now have a better idea of what I’m working with. The next step is to analyze the prompt so we can come up with a strategy to tackle this challenge.
For this step, I like to scribble my thoughts on a piece of paper 📝 However, feel free to use your computer, iPad, or other device that works best for you. Here, we need to analyze the prompt to understand exactly what is being asked of us.
In this case, the prompt seems to be broken down into 3 parts:
Find the users with 50% of events from the list aboveCount the number of users found in step (1)Select the client_id with the most number of users based on step (2)
Find the users with 50% of events from the list above
Count the number of users found in step (1)
Select the client_id with the most number of users based on step (2)
I’m also going to make the following assumptions:
I don’t need to use the customer_id and event_id columns
timing doesn’t matter
I’m calculating the 50% by dividing the number of events in the given list by the number of all events.
I’m counting the total number of users, even if they appear multiple times in the column. The prompt doesn’t specify to select the most popular client_id by identifying the distinct number of times a user appears in the dataset.
At this point in the interview, you would have taken the time to understand the challenge and communicated initial thoughts to the interviewer. In addition, feel free to ask the interviewer for clarification if you have any questions. Without the presence of an interviewer, let’s move onto the next step!
First, let’s get the users with 50% or more events in the following list: ‘video call received’, ‘video call sent’, ‘voice call received’, and ‘voice call sent.’ To get the percentage, we’ll use one-hot encoding in a CASE statement to return the values in the list as 1 and everything else as 0. The sum of that CASE statement will be the numerator. The denominator will be a COUNT of all elements in the event_type column.
CAST(SUM(            CASE                WHEN event_type IN ('video call received',                    'video call sent', 'voice call received',                    'voice call sent')                    THEN 1                ELSE 0            END) AS FLOAT)  / COUNT(event_type)
Next, we’ll wrap the conditional in a GROUP BY/HAVING clause. Remember that we need to filter on the user_id with at least 50% of events in the list. For that, we need to perform the aggregation, filter on the conditional, and finally, group by user_id.
SELECT      user_idFROM fact_eventsGROUP BY user_idHAVING CAST(SUM(            CASE                WHEN event_type IN ('video call received',                    'video call sent', 'voice call received',                    'voice call sent')                    THEN 1                ELSE 0            END) AS FLOAT)  / COUNT(event_type) >= 0.5
After completing the first step, we get the following output:
Now that we know that only 2 users have at least 50% of events in the list, let’s find out the number of users by client_id and user_id.
SELECT     client_id,     user_id,     COUNT(user_id)FROM fact_eventsWHERE user_id in         (SELECT              user_id        FROM fact_events        GROUP BY user_id        HAVING CAST(SUM(            CASE                WHEN event_type IN ('video call received',                    'video call sent', 'voice call received',                    'voice call sent')                    THEN 1                ELSE 0            END) AS FLOAT)  / COUNT(event_type) >= 0.5)GROUP BY     client_id,     user_idORDER BY COUNT (user_id) DESC
The output already points to our answer. Note that the client_id ‘desktop’ has 7 + 4 = 11 users while ‘mobile’ only has 3.
In our final step, we’ll clean up the output above to only return the client_id with the most number of users. Not too many changes to the SQL script are warranted here. Instead of grouping by client_id and user_id, I only group by client_id. I also make sure to limit the number of rows to return the client_id with the most number of users. If you don’t limit the selection, you’d also return “mobile” in the final output.
--final querySELECT     client_idFROM fact_eventsWHERE user_id in         (SELECT              user_id        FROM fact_events        GROUP BY user_id        HAVING CAST(SUM(            CASE                WHEN event_type IN ('video call received',                    'video call sent', 'voice call received',                    'voice call sent')                    THEN 1                ELSE 0            END) AS FLOAT)  / COUNT(event_type) >= 0.5)GROUP BY     client_idORDER BY COUNT(user_id) DESCLIMIT 1
Final output:
I hope you enjoyed this walkthrough exercise! There are plenty of resources for you to practice interview questions. Some of the most popular websites are Leetcode, StrataScratch, and InterviewQuery but I’m sure you can find many others that would give you the preparation you need to ace the DA interview. Don’t forget to share feedback or post a question in the comments below!
This post was last edited on October 30, 2021. The opinions expressed here belong solely to myself, and do not reflect the views of my employer.