Skip to main content
PYSPARK โ€ข LESSON 87

Conditional Aggregations per Group

How do we count successful and failed logins separately per account using conditional when() expressions?

Intermediateโฑ 3 Minutesโญ 460 XP
๐Ÿค” THE QUESTION

How do we count successful and failed logins separately per account using conditional when() expressions?

๐Ÿ’ก WHAT IS IT?

Nesting when() inside count() to compute pivot-like metrics for distinct status conditions per group.

๐ŸŽฏ WHAT IS IT USED FOR?

Security threat detection, fraud monitoring, and user authentication health tracking.

๐Ÿ’ป EXAMPLE
from pyspark.sql.functions import col, count, when

df.groupBy("account_id").agg(
    count(when(col("status") == "SUCCESS", 1)).alias("successful_logins"),
    count(when(col("status") == "FAILURE", 1)).alias("failed_logins")
).show()

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Conditional Aggregations per Group.

  • โœ“ Nest when() inside count()
  • โœ“ Compute success and failure counts per account
  • โœ“ Enable security anomaly detection