Skip to content

20. Pivot with Several Aggregations

Difficulty: Hard · Topics: Pivot, Unpivot & Rollup, Aggregations, Null Handling

For each customer, report the number and value of completed and returned orders side by side.

Return customer, completed_orders, completed_amount, returned_orders, returned_amount. Use 0 where a customer has no orders of that status. Other statuses (e.g. 'cancelled') are ignored, but a customer who only has those still appears with zeros.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

orders

customerstatusamount
anacompleted50
anacompleted30
anareturned30
bencompleted20
bencancelled99

Expected output

customercompleted_orderscompleted_amountreturned_ordersreturned_amount
ana280130
ben12000

Hints

Hint 1groupBy("customer").pivot("status", ["completed", "returned"]): listing the values skips a scan and fixes the column order.
Hint 2With several aggregations, Spark names the columns <value>_<alias>.
Hint 3Missing combinations come back as null; finish with fillna(0).

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