`

oracle 利用 lead 、lag 查询已有记录的下一条、上一条记录

阅读更多


 表的结构如下:

 



如要查询Staffno是6-1102的前一条记录

 

select * from staff where staff_no=(select c.p from (select staff_no,lag(staff_no,1,0)  over (order by staff_no) as p from staff) c where c.staff_no='6-1102')

结果:

STAFF_NO   STAFF_NAME           SEX 

---------- -------------------- --- -

6-1076     梁柄聪               男                                                                                                                                                                                                                                                                           


1 rows selected

 

如要查询其后一条记录

 

select * from staff where staff_no=(select c.n from (select staff_no,lead(staff_no,1,0)  over (order by staff_no) as n from staff) c where c.staff_no='6-1102')

 

结果:

 

STAFF_NO   STAFF_NAME           SEX 

---------- -------------------- --- -

6-1103     余志伟               男                                                                                                                    


1 rows selected




 查询第一条

 select * from (select s.*,row_number()over(order by staff_no ) rn from staff s) where rn=1 ;

 查询最后一条

 select * from (select s.*,row_number()over(order by staff_no desc ) rn from staff s) where rn=1 ;

  • 大小: 17.1 KB
2
2
分享到:
评论
2 楼 luoyonghui55 2014-08-12  
你这个要是能再写一些注释说明就更好了。
1 楼 yybb2277 2011-11-29  
太强了,谢谢

相关推荐

Global site tag (gtag.js) - Google Analytics