开发中经常用到当前行数据需要和临近行数据进行逻辑处理,这时跨行引用就派上了用场,注意以下结果中PREV_SAL的值:
--LAG分析函数,延后取数,在不使用自联接的情况下同时提供对表的多行数据的访问
SELECT hire_date, last_name, salary,
LAG(salary, 1, 0) OVER (ORDER BY hire_date) AS prev_sal
FROM employees
WHERE job_id = 'PU_CLERK'
ORDER BY hire_date;
执行结果:
HIRE_DATE LAST_NAME SALARY PREV_SAL
--------- ------------------------- ---------- ----------
18-MAY-03 Khoo 3100 0
24-JUL-05 Tobias 2800 3100
24-DEC-05 Baida 2900 2800
15-NOV-06 Himuro 2600 2900
10-AUG-07 Colmenares 2500 2600
--LEAD分析函数,向前取数
SELECT hire_date, last_name,
LEAD(hire_date, 1) OVER (ORDER BY hire_date) AS "NextHired"
FROM employees
WHERE department_id = 30
ORDER BY hire_date;
执行结果:
HIRE_DATE LAST_NAME Next Hired
--------- ------------------------- ----------
07-DEC-02 Raphaely 18-MAY-03
18-MAY-03 Khoo 24-JUL-05
24-JUL-05 Tobias 24-DEC-05
24-DEC-05 Baida 15-NOV-06
15-NOV-06 Himuro 10-AUG-07
10-AUG-07 Colmenares
当然,可以通过自连接的方式,使用rownum进行关联实现此功能。