Premium problem66. Two-Month Inactivity Churn

Hard Locked

users(user_id, signup_date) and monthly_activity(user_id, activity_month) where activity_month is the first day of the month.

For each month of 2026, count the users who churned in it. A user churns in a month when they had activity at some point before that month, and no activity in that month or the one immediately before it.

A user is counted only once, in the first month where that holds. Someone inactive all year does not get counted twelve times.

Return churn_month and churned_users for all twelve months, ordered by month, with 0 where nobody churned.

The "first month only" rule is what makes this awkward: the per-month test has to be evaluated for every month, then collapsed to one row per user.

Tables

monthly_activity

user_id  activity_month
-------  --------------
10       2026-01-01
10       2026-02-01
11       2025-11-01
13       2026-01-01
13       2026-06-01
13       2026-07-01

users

user_id  signup_date
-------  -----------
10       2026-01-01
11       2025-01-01
12       2026-01-01
13       2026-01-01

Expected result

churn_month  churned_users
-----------  -------------
2026-01-01   1
2026-02-01   0
2026-03-01   1
2026-04-01   1
2026-05-01   0
2026-06-01   0
2026-07-01   0
2026-08-01   0
... 4 more row(s)

Premium problem

This one's part of Premium. Unlock the full MySQL track plus every other premium problem on the site.

Write one SELECT query