lag 和lead 可以 获取结果集中,按一定排序所排列的当前行的上下相邻若干offset 的某个行的某个列(不用结果集的自关联);
lag ,lead 分别是向前,向后;
lag ,lead 分别是向前,向后;
lag 和lead 有三个参数,第一个参数是列名,第二个参数是偏移的offset,第三个参数是 超出记录窗口时的默认值.
我们先看下scott的emp表的两列数据:
select deptno, sal from scott.emp order by deptno
DEPTNO SAL
10 2450.00
10 5000.00
10 1300.00
20 2975.00
20 3000.00
20 1100.00
20 800.00
20 3000.00
30 1250.00
30 1500.00
30 1600.00
30 950.00
30 2850.00
30 1250.00
现在看看lag函数实现的功能:
select deptno, sal a,lag(sal, 1, sal) over(order by deptno) b from scott.emp;
DEPTNO
A
B
10
2450.00
2450 --ps:这里的之所以是2450是因为lag(sal, 1, sal)我让它给了他本身的值
10
5000.00
2450
10
1300.00
5000
20
2975.00
1300
20
3000.00
2975
20
1100.00
3000
20
800.00
1100
20
3000.00
800
30
1250.00
3000
30
1500.00
1250
30
1600.00
1500
30
950.00
1600
30
2850.00
950
30
1250.00
2850
而lead刚好和lag功能相反:
select deptno, sal a, lead(sal, 1, sal) over(order by deptno) b from scott.emp;
DEPTNO
A
B
10
2450.00
5000
10
5000.00
1300
10
1300.00
2975
20
2975.00
3000
20
3000.00
1100
20
1100.00
800
20
800.00
3000
20
3000.00
1250
30
1250.00
1500
30
1500.00
1600
30
1600.00
950
30
950.00
2850
30
2850.00
1250
30
1250.00
1250
另外那个偏移值1是可以随便取的如果是2那就是偏移两个值了
select deptno, sal a, lag(sal, 2,null) over(order by deptno) b
from scott.emp
DEPTNO
A
B
10
2450.00
--注意这里是null空了
10
5000.00
10
1300.00
2450 --A列1300的上两个值是多少?2450是吧
20
2975.00
5000
20
3000.00
1300
20
1100.00
2975
20
800.00
3000
20
3000.00
1100
30
1250.00
800
30
1500.00
3000
30
1600.00
1250
30
950.00
1500
30
2850.00
1600
30
1250.00
950
那其实lag,lead还可以加上分组偏移的
select deptno,
sal a,
lag(sal, 1, null) over(
partition by deptno order by deptno) b
from scott.emp
DEPTNO
A
B
10
2450.00
10
5000.00
2450
10
1300.00
5000
20
2975.00
20
3000.00
2975
20
1100.00
3000
20
800.00
1100
20
3000.00
800
30
1250.00
30
1500.00
1250
30
1600.00
1500
30
950.00
1600
30
2850.00
950
30
1250.00
2850
注意deptno不同的分组间的临界值你看明白了吧!
整理自网络
------------------------------------------------------------------------------
Blog: http://blog.csdn.net/tanzuai
IT群:69254049
Blog: http://blog.csdn.net/tanzuai
IT群:69254049