Using
<
http://www.myoracleportal.net/blog1.php/2009/03/18/using_oracle_analytics>
Analytic Functions in Oracle
There are two more analytical functions which are called LAG() and LEAD()
LAG() points to the immediately previous row of the current value
LEAD() points to the immediately next row of the current value
A simple example can demonstrate these functions.
Now If I want to sort the emp_ids under manager_id 101 in ascending order
then:
select emp_id from emp where mgr_id = 101 order by emp_id;
LEAD():
----
If I want the result like:
201, next value of 201 which is 202
202, next value of 202 which is 203
203, next value of 203 which is 204
204, next value of 204 which is NULL (because there is no emp_id for mgr_id
101 after 204)
we can do something like:
SQL> select emp_id,
2 lead(emp_id) over (partition by mgr_id order by emp_id) next_value
3 from emp
4 where mgr_id = 101;
EMP_ID NEXT_VALUE
---------- ----------
201 202
202 203
203 204
204
If we do not want NULL in the last row and instead we want zero there, we
could do:
SQL> select emp_id,
2 lead(emp_id,1,0) over (partition by mgr_id order by emp_id) next_value
3 from emp
4 where mgr_id = 101;
EMP_ID NEXT_VALUE
---------- ----------
201 202
202 203
203 204
204 0
LAG()
----
Now in the same case as above, if we want to have result like following
201, previous value of 201 which is NULL (because there is no emp_id for
mgr_id 101 before 201)
202, previous value of 202 which is 201
203, previous value of 203 which is 202
204, previous value of 204 which is 203
we can do something like:
SQL> select emp_id,
2 lag(emp_id) over (partition by mgr_id order by emp_id) previous_value
3 from emp
4 where mgr_id = 101;
EMP_ID PREVIOUS_VALUE
---------- --------------
201
202 201
203 202
204 203
If we do not want NULL in the first row, and instead we want zero there, we
could do:
SQL> select emp_id,
2 lag(emp_id,1,0) over (partition by mgr_id order by emp_id) previous_value
3 from emp
4 where mgr_id = 101;
EMP_ID PREVIOUS_VALUE
---------- --------------
201 0
202 201
203 202
204 203
Now Both LAG and LEAD together:
SQL> select emp_id,
2 lag(emp_id,1,0) over (partition by mgr_id order by emp_id) lag,
3 lead(emp_id,1,0) over (partition by mgr_id order by emp_id) lead
4 from emp
5 where mgr_id = 101;
EMP_ID LAG LEAD
---------- ---------- ----------
201 0 202
202 201 203
203 202 204
204 203 0
Best regards,
Abdoul Rahaman
IT Consultant
Globe Marine Services Co
Jeddah
Mobile : +966507654847