Skip to content

22. 7-Day Moving Average

Difficulty: Medium · Topics: Window Functions

The daily_sales table has one row per day. Add ma_7: the average revenue of the current day and the six rows before it (fewer at the start), rounded to 2 decimals.

Return day, revenue, ma_7, ordered by day. A day with missing revenue (null) is not counted in the average.

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

Sample data

daily_sales

dayrevenue
2024-01-01100
2024-01-02120
2024-01-0390
2024-01-04110
2024-01-05130
2024-01-0680
2024-01-07150
2024-01-08170
2024-01-0960

Expected output

dayrevenuema_7
2024-01-01100100
2024-01-02120110
2024-01-0390103.33
2024-01-04110105
2024-01-05130110
2024-01-0680105
2024-01-07150111.43
2024-01-08170121.43
2024-01-0960112.86

Hints

Hint 1A window ordered by day with a frame .rowsBetween(-6, Window.currentRow).
Hint 2F.avg over that frame ignores nulls automatically.
Hint 3Round the average, then sort by day.

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