在每个类别的SQL中选择排名前2位的销售额

时间:2018-09-02 11:29:01

标签: sql greatest-n-per-group

enter image description here

我有只想在每个班级中选择前2个销售额的表,结果是

Sophia   A 40
Jennifer A 15
Greg     B 50
Jeff     B 20
Stella   B 20 

2 个答案:

答案 0 :(得分:4)

您可以使用RANK

SELECT *
FROM (SELECT *, RANK() OVER(PARTITION BY class ORDER BY sales DESC) AS rnk
      FROM tab) sub
WHERE rnk <=2;

答案 1 :(得分:1)

窗口函数density_rank也满足样本数据的预期结果条件

 select * from
    (select * , dense_rank() over(partition by class order by scores DESC ) as rn 
     from tablea
     ) t where rn<=2