mysql或者oracle分组排序取前几条数据

mysql:

select a.*
from
(
select t1.*,(select count(*)+1 from 表 where 分组字段=t1.分组字段 and 排序字段<t1.排序字段) as group_id
from 表 t1
) a
where a.group_id<=3

Oracle:

SELECT t.*         
   FROM (SELECT ROW_NUMBER() OVER(PARTITION BY 分组字段 ORDER BY 排序字段 DESC) rn,         
         b.*         
         FROM 表 b) t         
  WHERE t.rn <= 3  ;

猜你喜欢

转载自www.cnblogs.com/caoql/p/9179374.html