有时候我们需要
先排序,后取值
或者是取分组后的前几名
语法:
row_number() over ( partition by 分组字段 order by 排序字段 [desc])
具体用法:
select * from (
select r.*,row_number() over(partition by col1 order by col2 desc) rn from table r
) where rn between 1 and 2;
解释: 先按col1分组,然后按col2降序排序,每组取排名1,2的数据