Interview Questions/SQL/Multi-Period Cohort Retention Analysis

Multi-Period Cohort Retention Analysis

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a Users table (with signup dates) and an Activity table (with activity dates). Using a recursive CTE to generate month offsets 0 through 3, compute for each signup cohort (by YYYY-MM) what percentage of users were active in each of the 4 months starting from their signup month. Offset 0 = the signup month itself, offset 1 = the month after, etc. Return (cohort_month, offset_month, cohort_size, active_users, retention_pct) ordered by cohort_month, then offset_month. retention_pct should be ROUND()ed to 1 decimal place. Table: Users

Column NameTypeDescription
user_idINTPrimary key
signup_dateDATEDate user signed up

Table: Activity

Column NameTypeDescription
user_idINTReferences Users
activity_dateDATEDate user was active

Database Schema (Inferred)

Users

Column NameExample Value
user_id1
signup_date2024-01-15

Activity

Column NameExample Value
user_id1
activity_date2024-01-15

Example

Users

user_idsignup_date
12024-01-15
22024-01-20
32024-01-25
42024-02-05
52024-02-10

Activity

user_idactivity_date
12024-01-15
12024-02-10
12024-03-05
12024-04-12
22024-01-20
22024-02-18
22024-03-22
32024-01-25
32024-02-28
42024-02-05
42024-03-10
42024-04-15
52024-02-10
52024-03-20

Output

cohort_monthoffset_monthcohort_sizeactive_usersretention_pct
2024-01033100
2024-01133100
2024-0123266.7
2024-0133133.3
2024-02022100
2024-02122100
2024-0222150
2024-023200

Explanation:

Assign users to cohorts by STRFTIME('%Y-%m', signup_date). Generate offsets 0-3 with a recursive CTE. For each cohort+offset, count distinct users who have any activity row in the target month (cohort_month + offset months). Divide by cohort size.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Users

user_idsignup_date
12024-01-15
22024-01-20
32024-01-25
42024-02-05
52024-02-10

Activity

user_idactivity_date
12024-01-15
12024-02-10
12024-03-05
12024-04-12
22024-01-20
22024-02-18
22024-03-22
32024-01-25
32024-02-28
42024-02-05
42024-03-10
42024-04-15
52024-02-10
52024-03-20

Output

cohort_monthoffset_monthcohort_sizeactive_usersretention_pct
2024-01033100
2024-01133100
2024-0123266.7
2024-0133133.3
2024-02022100
2024-02122100
2024-0222150
2024-023200