Skip to content
Advertisement

Cannot use SQL Lead function correctly

I have a table with 4 columns: date, event_name, video_id and user_id.

I need to write a query that will return the number of users who viewed at least one video in a given day and the number of those users who returned the next day to view at least one video. The video_play event signifies that a video was played by a user.

Here’s some sample data upon which I need to base my query:

This is how the output should look:

This query completes the first half of the querying task, but I cannot figure out the second half:

Thanks.

Advertisement

Answer

If you make a CTE which lists all the distinct users who have watched a video on a given day, that can be used to give a count of users who viewed a video on a given day. You can then join it to itself on the condition that the date in the second table is the next day, and the user_id is the same, to get the count of those who viewed videos on that day and the next one:

Output:

Demo on dbfiddle

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement