【Oracle】【9】取前N条记录——rownum和row_number() over()的使用

前言:

1,取前10条数据

2,取第10条到第20条的数据

3,排序后再取前10条

4,分组后取前10条

正文:

1,最普通的情况,取前10条数据

select * from table where rownum <= 10

2,取第10条到第20条的数据

注:因为rownum本身只能用 <=的比较方式,所以用rownum rn把rownum转成实例,这样就可以做 >=的比较了

select * from (select *, rownum rn from table ) where rn >= 10 and rn <= 20

3,排序后再取前10条

select * from (select * from table order by name desc) where rownum <= 10

有另外一种写法,效率更高,但是只对主键字段有效。其他情况下会先取前10条数据,再对这10条数据排序

select * from table where rownum <= 10 order by name desc

4,分组后取前10条。根据id分组,在分组内部根据name排序,再取前10条

select * from (select t.*, row_number() over(partition by id order by name desc) rn from table t ) where rownum <= 10

参考博客:

Oracle中查询前10条记录,类似top 方法 - lex.lin - 博客园
https://www.cnblogs.com/lexlin/archive/2012/06/19/2554315.html

猜你喜欢

转载自www.cnblogs.com/huashengweilong/p/10802839.html