18. Conversion Funnel
Difficulty: Hard · Topics: Aggregations, Conditional Logic
The events table has user_id and step ('visit', 'signup', 'purchase'; users may repeat steps). A user counts at a step only if they also completed every earlier step.
Return a single row: visits, signups, purchases (user counts) and signup_rate and purchase_rate (percent of the previous step, 1 decimal; null if the previous step is 0).
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
events
| user_id | step |
|---|---|
| 1 | visit |
| 1 | signup |
| 1 | purchase |
| 2 | visit |
| 2 | signup |
| 3 | visit |
| 4 | visit |
| 4 | visit |
Expected output
| visits | signups | purchases | signup_rate | purchase_rate |
|---|---|---|---|---|
| 4 | 2 | 1 | 50 | 50 |
Hints
Hint 1
First reduce to one row per user with a 0/1 flag per step:F.max(F.when(step == "visit", 1).otherwise(0)).Hint 2
A user reaches signup only if visit AND signup: multiply the flags.Hint 3
Then sum the flags across users and compute the rates.Learn the concepts
- when / otherwise · 4 min read. CASE WHEN logic inside a column: first match wins, and a missing otherwise means null.
- groupBy + agg · 4 min read. Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).
- withColumn · 6 min read. Add or replace one column, and why calling it in a long loop slows Spark down.
PySpark functions you'll practise
- groupBy
- agg
- sum
- max
- when / otherwise
- withColumn
Related problems
- Conditional Aggregation · Medium · Aggregations, Conditional Logic
- Entry and Exit Pages (MAX_BY / MIN_BY) · Medium · Aggregations
- New Users per Day · Medium · Aggregations
- Median and 90th Percentile · Medium · Aggregations
- Find Repeat Customers · Easy · Aggregations, Filtering & Selection
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice