Skip to content

21. 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_idevent_type
1view
1view
1click
1purchase
2view
2click

Expected output

user_idviewsclickspurchasesconversion
12110.5
21100

Hints

Hint 1One groupBy with several F.sum(F.when(condition, 1).otherwise(0)) columns counts each event type in a single pass.
Hint 2Division by zero yields null in Spark (with ANSI mode off), which is what we want.
Hint 3F.round(x, 2) for the ratio.

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems