Skip to main content
PYSPARK โ€ข LESSON 86

Custom Multi-Metric Aggregations with agg()

How do we compute headcount, total spend, average comp, and maximum salary per department in one pass?

Intermediateโฑ 2 Minutesโญ 440 XP
๐Ÿค” THE QUESTION

How do we compute headcount, total spend, average comp, and maximum salary per department in one pass?

๐Ÿ’ก WHAT IS IT?

Passing multiple aggregate functions into agg() to calculate comprehensive group statistics in a single shuffle.

๐ŸŽฏ WHAT IS IT USED FOR?

Departmental budget audits, organizational compensation analysis, and executive HR reports.

๐Ÿ’ป EXAMPLE
from pyspark.sql.functions import avg, col, count, max, sum

df.groupBy("department").agg(
    count(col("emp_id")).alias("headcount"),
    sum(col("salary")).alias("dept_spend"),
    avg(col("salary")).alias("avg_comp"),
    max(col("salary")).alias("top_salary")
).show()

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Custom Multi-Metric Aggregations with agg().

  • โœ“ Compute count, sum, avg, and max in single agg()
  • โœ“ Alias all departmental metrics
  • โœ“ Produce executive HR summary