14. Conditional Aggregation
Difficulty: Medium · Topics: Aggregations, Conditional Logic
From the events table compute, per user_id, how many views, clicks and purchases they made, plus conversion = purchases ÷ views, rounded to 2 decimals.
A user with no views has a null conversion. Return user_id, views, clicks, purchases, conversion.
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 | event_type |
|---|---|
| 1 | view |
| 1 | view |
| 1 | click |
| 1 | purchase |
| 2 | view |
| 2 | click |
Expected output
| user_id | views | clicks | purchases | conversion |
|---|---|---|---|---|
| 1 | 2 | 1 | 1 | 0.5 |
| 2 | 1 | 1 | 0 | 0 |
Hints
Hint 1
OnegroupBy with several F.sum(F.when(condition, 1).otherwise(0)) columns counts each event type in a single pass.Hint 2
Division by zero yieldsnull in Spark (with ANSI mode off), which is what we want.Hint 3
F.round(x, 2) for the ratio.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
- when / otherwise
- withColumn
Related problems
- Entry and Exit Pages (MAX_BY / MIN_BY) · Medium · Aggregations
- New Users per Day · Medium · Aggregations
- Median and 90th Percentile · Medium · Aggregations
- Conversion Funnel · Hard · Aggregations, Conditional Logic
- 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