1. 程式人生 > >Oracle 子查詢,按降序排列,取前n條

Oracle 子查詢,按降序排列,取前n條

比如,有一個student 表:

id             student_name     

1                                  s1

2                                  s2

03                                s3

04                                s4

05                                s5

06                                s6

07                                s7

08                                s8

09                                s9

這些id 不一致,比如我想把id 變成 1, 2, 3(而不用03),4, 5 , 6, 7, 8, 9

可執行如下操作:

update  student a set a.id =(select substr(b.id,-1) from student b where b.id=a.id)
where a.id >2;

commit;

之後結果變為:

id             student_name     

1                                  s1

2                                  s2

                               s3

                               s4

                               s5

                               s6

7                                s7

8                                s8

                               s9

之後,想通過子查詢的方式,按倒序顯示前6條記錄:

select * from (select * from student order by id desc)
where rownum <= 6;

結果為:

id             student_name     

9                    s9

8                    s8

7                    s7

6                    s6

5                    s5

4                    s4