Monthly Customer Churn Count

SQL coding challenge · Difficulty: hard · Topic: Aggregation · +150 XP

Problem

A customer has churned in a month if they were active the month before and are absent this month. Count the churned customers per month.

Schema — `monthly_active`

| Column | Type |
| --- | --- |
| customer_id | INT |
| month_num | INT |

Example Input — `monthly_active`

| customer_id | month_num |
| --- | --- |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 5 | 1 |
| 1 | 2 |
| 2 | 2 |
| 4 | 2 |
| 1 | 3 |
| 4 | 3 |

Expected Output

| month_num | churned_customers |
| --- | --- |
| 2 | 2 |
| 3 | 1 |

Explanation

Worked through: month 1 had customers 1, 2, 3 and 5. Month 2 has 1, 2 and 4 — so 3 and 5 churned, a count of 2. Month 3 has 1 and 4, so customer 2 churned, a count of 1. Customer 4 is new in month 2, which is growth, not churn.

Month 1 has no month before it, so it produces no row at all. The last month produces no row either — there is no data yet for the month after it, and counting everyone as churned there is the classic off-by-one in this question.

Notes

What this SQL challenge teaches you

“Monthly Customer Churn Count” is a hard-level SQL challenge focused on Aggregation. Working through it gives you hands-on practice with NOT EXISTS, Self Join, Churn, Aggregation — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.

Concepts covered

How to approach it

If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:

  1. Join each month to the one before it: prev.month_num = cur.month_num - 1.
  2. NOT EXISTS finds customers from the previous month with no row in the current one.
  3. Driving the join off (SELECT DISTINCT month_num ...) is what stops the final month producing a bogus row.

How to practise it on PySpark.in

Open the challenge, write your SQL query in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.

Related SQL challenges

Frequently asked questions

Do I need to install Spark or a database to solve this?

No. The SQL environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.

Is this challenge free?

Yes - the problem, the sample dataset, the hints and unlimited test runs are free.

What level is it?

It is rated hard and covers Aggregation.

Solve this challenge free on PySpark.in