Skip to main content
PYSPARK • LESSON 233

Top-N Ranked Records per Category

How can we select the top 3 best-selling products in each department without writing repetitive subqueries?

Advanced3 Minutes820 XP
🤔 THE QUESTION

How can we select the top 3 best-selling products in each department without writing repetitive subqueries?

💡 WHAT IS IT?

dense_rank() over department partitions orders products by revenue, allowing filtering for rank <= 3.

🎯 WHAT IS IT USED FOR?

Generating executive leaderboards, category-level bestseller carousels, and top regional performers.

💻 EXAMPLE
w = Window.partitionBy("category").orderBy(col("sales_amount").desc())
df_top_3 = df.withColumn("rank", dense_rank().over(w)).filter(col("rank") <= 3)

🎯 Mission Objectives

Practice typing production-grade PySpark code for Top-N Ranked Records per Category.

  • dense_rank() function
  • Category-level ranking
  • Top-N record extraction