Skip to main content
PYSPARK โ€ข LESSON 113

Cumulative Running Totals with Window Frames

How do we calculate a running cumulative spend total for each customer from their first order to the current order?

Advancedโฑ 2 Minutesโญ 600 XP
๐Ÿค” THE QUESTION

How do we calculate a running cumulative spend total for each customer from their first order to the current order?

๐Ÿ’ก WHAT IS IT?

Using rowsBetween(Window.unboundedPreceding, Window.currentRow) to bound calculations from partition start to current row.

๐ŸŽฏ WHAT IS IT USED FOR?

Lifetime customer value tracking, cumulative revenue burn rates, and financial ledger running balances.

๐Ÿ’ป EXAMPLE
from pyspark.sql.window import Window
from pyspark.sql.functions import col, sum

window_spec = Window.partitionBy("customer_id") \
    .orderBy("order_date") \
    .rowsBetween(Window.unboundedPreceding, Window.currentRow)

df = df.withColumn("running_total", sum(col("amount")).over(window_spec))

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Cumulative Running Totals with Window Frames.

  • โœ“ Define unboundedPreceding frame specification
  • โœ“ Calculate running cumulative sum
  • โœ“ Track customer cumulative spending