1

enter image description here

I have the table which I want select only top 2 sales in each class, the result is

Sophia   A 40
Jennifer A 15
Greg     B 50
Jeff     B 20
Stella   B 20 
KEVINBOSS
  • 149
  • 1
  • 1
  • 11

2 Answers2

4

You could use RANK:

SELECT *
FROM (SELECT *, RANK() OVER(PARTITION BY class ORDER BY sales DESC) AS rnk
      FROM tab) sub
WHERE rnk <=2;
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
1

window function dense_rank also fulfil expected result condition of sample data

 select * from
    (select * , dense_rank() over(partition by class order by scores DESC ) as rn 
     from tablea
     ) t where rn<=2
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63