Spark sql top n per group

10,758

You can use the window function feature that was added in Spark 1.4 Suppose that we have a productRevenue table as shown below. enter image description here

the answer to What are the best-selling and the second best-selling products in every category is as follows

SELECT product,category,revenue FROM 
   (SELECT product,category,revenue,dense_rank() 
         OVER (PARTITION BY category ORDER BY revenue DESC) as rank 
    FROM productRevenue) tmp 
WHERE rank <= 2

Tis will give you the desired result

Share:
10,758
Georg Heiler
Author by

Georg Heiler

I am a Ph.D. candidate at the Vienna University of Technology and Complexity Science Hub Vienna as well as a data scientist in the industry.

Updated on June 11, 2022

Comments