在Oracle中的SQL查询中获取固定数量的行

时间:2014-09-10 11:04:03

标签: sql oracle informix

请帮我在Oracle数据库中编写SQL查询。有一个名为tbl的表,它有12行。我想首先选择前4行然后选择接下来的4行和最后4行。

任何人都可以告诉我如何在Informix中执行此操作。

3 个答案:

答案 0 :(得分:2)

编辑:现在应该用3级选择修复:

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

第一部分。

第二和第三部分:

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

答案 1 :(得分:2)

没有任何东西称为第一行,最后一行," n"行,除非您明确指定ORDER BY,然后选择所需的行。

让我展示Oracle Database 12c中前N个查询的行限制条款的新技术

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.

前4行:

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

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

接下来的4行(查看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

最后,接下来的4行OFFSET 8行:

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

干净,不是吗?

答案 2 :(得分:1)

您可以使用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;
/

如果您使用的是order by条款,请使用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;
/