Fetch a fixed number of rows in SQL query in Oracle [duplicate]

≡放荡痞女 提交于 2019-12-02 14:33:14

问题


Please help me to write an SQL query in the Oracle database. There is table called tbl and it has 12 rows. I want to select first 4 rows first then next 4 and the last 4 rows.

Can any anyone tell me how can I do this in Informix.


回答1:


You can use rownum:

select * from (select t.*, rownum rn from tbl t) where rn between 1 and 4;
/
select * from (select t.*, rownum rn from tbl t) where rn between 5 and 8;
/
select * from (select t.*, rownum rn from tbl t) where rn between 9 and 12;
/

If you're using order by clause then use row_number() (documentation)

select * from (select t.*, row_number() over (order by column_name) rn from tbl t) where rn between 1 and 4;
/
select * from (select t.*, row_number() over (order by column_name) rn from tbl t) where rn between 5 and 8;
/
select * from (select t.*, row_number() over (order by column_name) rn from tbl t) where rn between 9 and 12;
/



回答2:


There is nothing called as first rows, last rows, "n" rows unless you explicitly specify an ORDER BY and then select the required rows.

Let me show a new technique of Row Limiting Clause for Top-N Queries in Oracle Database 12c :

SQL> DROP TABLE order_test;

Table dropped.

SQL>
SQL> CREATE TABLE order_test (
  2    val  NUMBER
  3  );

Table created.

SQL>
SQL> INSERT ALL
  2    INTO order_test
  3    INTO order_test
  4  SELECT level
  5  FROM   dual
  6  CONNECT BY level <= 10;

20 rows created.

SQL>
SQL> COMMIT;

Commit complete.

SQL>
SQL> select * from order_test order by val;

       VAL
----------
         1
         1
         2
         2
         3
         3
         4
         4
         5
         5
         6
         6
         7
         7
         8
         8
         9
         9
        10
        10

20 rows selected.

First 4 rows :

SQL> SELECT val
  2  FROM   order_test
  3  ORDER BY VAL
  4  FETCH FIRST 4 ROWS ONLY;

       VAL
----------
         1
         1
         2
         2

Next 4 rows(look at OFFSET) :

SQL> SELECT val
  2  FROM   order_test
  3  ORDER BY VAL
  4  OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;

       VAL
----------
         3
         3
         4
         4

Finally, next 4 rows with OFFSET 8 rows :

SQL> SELECT val
  2  FROM   order_test
  3  ORDER BY VAL
  4  OFFSET 8 ROWS FETCH NEXT 4 ROWS ONLY;

       VAL
----------
         5
         5
         6
         6

Neat, isn't it?




回答3:


EDIT: now should be fixed with 3-level select:

select * from (
  select q1.*, rownum as rn from (   --get correct rownum 
      select * from tbl order by column --get correct order
  ) q1
) q2
 where q2.rn between 1 and 4; -- filter

for first part.

For second and third part:

 where q2.rn between 5 and 8
 where q2.rn between 9 and 12


来源:https://stackoverflow.com/questions/25763745/fetch-a-fixed-number-of-rows-in-sql-query-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!