Skip to content

23. Trailing 3 Calendar Days (Range Frame)

Difficulty: Hard · Topics: Window Functions, Dates, Filtering & Selection

Some days have no sales, so they are missing from sales. For each row, compute rev_3d: total revenue over the last 3 calendar days (the day itself and the two days before it), not the last 3 rows.

Return day, revenue, rev_3d, ordered by day.

Row order matters for this problem. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

sales

dayrevenue
2024-05-0110
2024-05-0220
2024-05-0440
2024-05-055
2024-05-097

Expected output

dayrevenuerev_3d
2024-05-011010
2024-05-022030
2024-05-044060
2024-05-05545
2024-05-0977

Hints

Hint 1rowsBetween(-2, 0) would look back 3 rows; with gaps that spans more than 3 days.
Hint 2A range frame needs a numeric ordering column: turn the date into a day number with F.datediff("day", F.lit("2000-01-01")).
Hint 3Then use Window.orderBy("day_num").rangeBetween(-2, 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