Skip to main content
PYSPARK • LESSON 83

Segment Totals with sum()

How do we calculate total sales revenue by geographic region using agg() and sum()?

Intermediate2 Minutes400 XP
🤔 THE QUESTION

How do we calculate total sales revenue by geographic region using agg() and sum()?

💡 WHAT IS IT?

groupBy('region').agg(sum('sales')) groups by territory and computes the total monetary sales.

🎯 WHAT IS IT USED FOR?

Regional performance leaderboards, sales compensation tracking, and regional quota monitoring.

💻 EXAMPLE
from pyspark.sql.functions import col, sum

df.groupBy("region").agg(sum(col("sales")).alias("total_sales")).show()

🎯 Mission Objectives

Practice typing production-grade PySpark code for Segment Totals with sum().

  • Group by geographic region
  • Sum regional sales totals
  • Alias output total sales column