Calculate Playback Counts per Stream
AdiaData Scientist · Technical ScreenLast updated
This question tests the ability to perform relational database joins and use aggregate functions (COUNT) with grouping to summarize event-level data.
Problem Statement
You are given two tables representing playback events on a media platform. Your task is to calculate the total number of playback events for each stream and include the corresponding streamer's name.
Tables
-
streamstable:stream_id(int): Unique identifier for a stream.streamer_name(varchar): Name of the streamer.
-
playback_eventstable:event_id(int): Unique identifier for the event.stream_id(int): ID of the stream where the event occurred.
Task
Write a SQL query that returns the stream_id, streamer_name, and the total count of playback events for each stream. If a stream has zero events, it should still appear in the list with a count of 0.
Example Input
streams:
| stream_id | streamer_name |
|---|---|
| 101 | Alice |
| 102 | Bob |
playback_events:
| event_id | stream_id |
|---|---|
| 1 | 101 |
| 2 | 101 |
| 3 | 102 |
Example Output
| stream_id | streamer_name | event_count |
|---|---|---|
| 101 | Alice | 2 |
| 102 | Bob | 1 |
Constraints
stream_idis the primary key instreams.playback_eventscan contain multiple events perstream_id.- Ensure all streams are included, even if they have no corresponding events in the
playback_eventstable.
Hints
Hint 1
Use a JOIN clause to combine the two tables based on the common 'stream_id' column.
Hint 2
To include streams with zero events, consider using a LEFT JOIN starting from the 'streams' table.
Hint 3
Use the GROUP BY clause on 'stream_id' and 'streamer_name' and use the COUNT() function to tally events.
Follow-up questions
- How would you modify the query to only return streams that have more than 100 playback events?
- If we wanted to calculate the average number of events per streamer, how would you approach that using a subquery or a CTE?
- What would be the performance impact of adding an index on the 'stream_id' column in both tables?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.