How can we select the top 3 best-selling products in each department without writing repetitive subqueries?
dense_rank() over department partitions orders products by revenue, allowing filtering for rank <= 3.
Generating executive leaderboards, category-level bestseller carousels, and top regional performers.
w = Window.partitionBy("category").orderBy(col("sales_amount").desc())
df_top_3 = df.withColumn("rank", dense_rank().over(w)).filter(col("rank") <= 3)Practice typing production-grade PySpark code for Top-N Ranked Records per Category.