前言:
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
淺談Oracle中Rownum的排序和比較 - bboyuan - ITeye博客
