Friday, February 11, 2011

LAG() & LEAD() Analytical Functions in PL/SQL

LAG is an Analytical function that can be used to get the value of an attribute of the previous row. If you want to retrieve the value of the next row, use LEAD instead of lag. 

In the below example we are extracting the Current, Previous and Next expected Salary of the Departments

SELECT e.ename, d.dname, e.sal
  FROM emp e, dept d
 WHERE e.deptno = d.deptno
 ORDER BY ROWNUM, d.dname



Using LEAD & LAG Function:

SELECT ROWNUM,
       d.dname dept,
       LAG(e.sal, 1, 0) OVER(ORDER BY ROWNUM, d.dname) prev_salary,
       LEAD(e.sal, 1, 0) OVER(ORDER BY ROWNUM, d.dname) next_salary,
       e.sal curr_salary
  FROM emp e, dept d
 WHERE e.deptno = d.deptno




No comments:

Post a Comment