KatInterview

Seven-Day Return Rate from a Daily Posting Log

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionsretention

Last updated

From a per-day post count table, find each user's first active date, their first-week post total, and the share of users who were active on the seventh day of their life on the platform.

You are given a table post_activity that records how many posts each user made on each calendar day.

ColumnMeaning
user_ididentifier of the user
post_datecalendar date of the activity
postsnumber of posts made by the user that day

Sample data:

user_idpost_dateposts
12023-01-013
12023-01-022
22023-04-101
22023-04-114
32023-05-055

There is no separate signup table, so a user's join date has to be inferred from this log.

Tasks

  1. For each user, determine the join date, defined as the earliest post_date on which they posted.
  2. For each user, compute the total number of posts made during their first 7 days on the platform (the join date and the following six days).
  3. Compute the Day-7 retention rate: the number of users who posted on their 7th day, divided by the number of users who posted on their 1st day.

Write the solution in SQL, and optionally show the equivalent in Python (pandas).

What to cover in your answer

  • State your convention for numbering days (is the join date Day 1 or Day 0?) and show how the choice affects the query.
  • Show the output for the sample data.
  • Discuss edge cases: duplicate rows for one user-day, rows with zero posts, users too new to have reached Day 7, and users with gaps in activity.

Hints

Hint 1

Attach each user's join date to every one of their rows without collapsing the table. A window MIN over a partition by user does exactly that.

Hint 2

Subtract the join date from each post_date to get a day offset, then use CASE expressions on that offset: one to sum posts for offsets 0 to 6, and others to produce 0/1 flags for offset 0 and offset 6.

Hint 3

Take MAX of each flag per user to get a boolean, then divide the sum of the Day-7 flags by the sum of the Day-1 flags. Remember to avoid integer division and to think about users who joined too recently to have a Day 7.