從表mytest(a,b,c,d)中選取以c排序後的第N至N+3行

tian1982tian發表於2011-04-13

  在ORACLE中選取表中的N行道N+3行資料有兩種方法,如下:

SQL> conn scott/tiger
Connected.
SQL> SELECT tname FROM tab;

TNAME
------------------------------
BONUS
DEPT
EMP
SALGRADE
STUDENT
TEST

6 rows selected.

SQL> CREATE TABLE mytest
  2  (
  3   a number,
  4   b number,
  5   c number
  6  );

Table created.

SQL> INSERT INTO  mytest values(1,1,1);

1 row created.

SQL> INSERT INTO  mytest values(2,2,2);

1 row created.

SQL> INSERT INTO  mytest values(3,3,3);

1 row created.

SQL> INSERT INTO  mytest values(4,4,4);

1 row created.

SQL> INSERT INTO  mytest values(5,5,5);

1 row created.

SQL> INSERT INTO  mytest values(6,6,6);

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM mytest;

         A          B          C
---------- ---------- ----------
         1          1          1
         2          2          2
         3          3          3
         4          4          4
         5          5          5
         6          6          6

6 rows selected.

SQL>

以下為查詢方法:

方法一:

SQL> SELECT * FROM (
  2  SELECT * FROM mytest ORDER BY  c) WHERE rownum<=5
  3  minus
  4  SELECT * FROM (
  5  SELECT * FROM mytest ORDER BY  c) WHERE rownum<=2;

         A          B          C
---------- ---------- ----------
         3          3          3
         4          4          4
         5          5          5

方法二:

SQL> SELECT * FROM
  2  (SELECT  a.*,row_number() OVER(PARTITION BY 1 ORDER BY  c) rn FROM mytest a) a
  3  WHERE rn BETWEEN 3 AND 5;

         A          B          C         RN
---------- ---------- ---------- ----------
         3          3          3          3
         4          4          4          4
         5          5          5          5

SQL>

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16400082/viewspace-692427/,如需轉載,請註明出處,否則將追究法律責任。

相關文章