Skip to content

38. Price Valid at Order Time (Range Join)

Difficulty: Hard · Topics: Joins, Null Handling, Filtering & Selection

prices keeps price history: each row is valid from valid_from to valid_to inclusive, and valid_to is null for the current price. Dates are YYYY-MM-DD strings.

For every row in orders, find the price that was valid on order_date and compute revenue = qty × price. Keep orders with no valid price (price and revenue null).

Return order_id, product, order_date, price, revenue.

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_idproductorder_dateqty
1pen2024-01-1510
2pen2024-03-015
3ink2024-02-102

prices

productpricevalid_fromvalid_to
pen22024-01-012024-02-29
pen32024-03-01null
ink72024-01-01null

Expected output

order_idproductorder_datepricerevenue
1pen2024-01-15220
2pen2024-03-01315
3ink2024-02-10714

Hints

Hint 1This is a join on the product and a date range, not just a key.
Hint 2Treat an open-ended valid_to as far in the future: F.coalesce("valid_to", F.lit("9999-12-31")).
Hint 3Use a left join so unmatched orders survive.

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