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?

Advancedโฑ 3 Minutesโญ 820 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