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_id | customer_id | order_date | amount |
|---|---|---|---|
| 1 | 1 | 2024-01-05 | 100 |
| 2 | 1 | 2024-02-10 | 250 |
| 3 | 2 | 2024-01-20 | 75 |
| 4 | 2 | 2024-01-25 | 60 |
| 5 | 3 | 2024-03-01 | 500 |
Expected output
| customer_id | order_id | order_date | amount |
|---|---|---|---|
| 1 | 2 | 2024-02-10 | 250 |
| 2 | 4 | 2024-01-25 | 60 |
| 3 | 5 | 2024-03-01 | 500 |
Hints
Hint 1
Define a window:Window.partitionBy("customer_id").orderBy(F.col("order_date").desc()).Hint 2
AddF.row_number().over(w) as a new column; the latest order gets 1.Hint 3
Filterrn == 1 and drop the helper column.Learn the concepts
- row_number / rank · 4 min read. Number and rank rows inside a window, and how the three ranking functions treat ties.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
- filter / where · 5 min read. Keep the rows that match a condition, and the null and operator traps that silently drop data.
PySpark functions you'll practise
- Row Number
- Window spec
- filter
- select
- withColumn
- orderBy
Related problems
- Top Two Salary Levels per Department · Medium · Window Functions, Filtering & Selection
- Running Total by Region · Medium · Window Functions
- Month-over-Month Change · Medium · Window Functions
- 7-Day Moving Average · Medium · Window Functions
- Customer Spend Quartiles (NTILE) · Medium · Window Functions
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