SQL ROWNUM如何返回特定范围之间的行

时间:2010-12-29 09:05:56

标签: sql database oracle rownum

如何返回特定范围的ROWNUM值?

我正在尝试以下方法:

select * from maps006 where rownum >49 and rownum <101

这只返回与<运算符匹配的行。

7 个答案:

答案 0 :(得分:54)

 SELECT * from
 (
 select m.*, rownum r
 from maps006 m
 )
 where r > 49 and r < 101

答案 1 :(得分:24)

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

请注意双嵌套视图。在ROWNUM之前评估ORDER BY,因此需要正确的编号。

如果省略ORDER BY条款,则不会获得一致的订单。

答案 2 :(得分:11)

我知道这是一个老问题,但是,在最新版本中提及新功能非常有用。

Oracle 12c 开始,您可以使用新的前N行限制功能。无需编写子查询,也不需要依赖ROWNUM。

例如,以下查询将按升序将员工退回到第4高到第7高薪之间:

SELECT SUM(appointments.price + line_items.price) AS total_sum
FROM appointments
 INNER JOIN 
(
SELECT line_items.appointment_id,SUM(price) as price
line_items
GROUP BY appointment_id 
) line_items ON line_items.appointment_id = appointments.id

答案 3 :(得分:5)

我一直在寻找解决方案,并发现这很棒 article explaining the solution 相关摘录

  

我最喜欢使用ROWNUM的是分页。在这种情况下,我使用   ROWNUM获取结果集的行N到M.一般形式如下   如下:

select * enter code here
  from ( select /*+ FIRST_ROWS(n) */ 
  a.*, ROWNUM rnum 
      from ( your_query_goes_here, 
      with order by ) a 
      where ROWNUM <= 
      :MAX_ROW_TO_FETCH ) 
where rnum  >= :MIN_ROW_TO_FETCH;

现在有了一个真实的例子(得到行148,149和150):

select *
    from
  (select a.*, rownum rnum
     from
  (select id, data
     from t
   order by id, rowid) a
   where rownum <= 150
  )
   where rnum >= 148;

答案 4 :(得分:2)

SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNum, * FROM maps006) AS DerivedTable
WHERE RowNum BETWEEN 49 AND 101

答案 5 :(得分:2)

您也可以使用CTE with clause。

WITH maps AS (Select ROW_NUMBER() OVER (ORDER BY Id) AS rownum,* 
from maps006 )

SELECT rownum, * FROM maps  WHERE rownum >49 and rownum <101  

答案 6 :(得分:2)

select * 
from emp 
where rownum <= &upperlimit 
minus 
select * 
from emp 
where rownum <= &lower limit ;