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
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
You could use RANK
:
SELECT *
FROM (SELECT *, RANK() OVER(PARTITION BY class ORDER BY sales DESC) AS rnk
FROM tab) sub
WHERE rnk <=2;
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