Skip to content

39. Latest Order per Customer

Difficulty: Medium · Topics: Window Functions, Filtering & Selection

For each customer in orders, return their most recent order (largest order_date).

Return the columns customer_id, order_id, order_date, amount. Dates are ISO strings (YYYY-MM-DD) and a customer never has two orders on the same date.

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

Sample data

orders

order_idcustomer_idorder_dateamount
112024-01-05100
212024-02-10250
322024-01-2075
422024-01-2560
532024-03-01500

Expected output

customer_idorder_idorder_dateamount
122024-02-10250
242024-01-2560
352024-03-01500

Hints

Hint 1Define a window: Window.partitionBy("customer_id").orderBy(F.col("order_date").desc()).
Hint 2Add F.row_number().over(w) as a new column; the latest order gets 1.
Hint 3Filter rn == 1 and drop the helper column.

Learn the concepts

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 · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance

Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice