这两个函数是计算偏移量的分析函数,可以查出同一个字段下一个或上一个所关联字段的值,并作为新列放于结果集中。
用法:
■LAG (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
■LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
value_expression - 可以是表的一列,也可以是一个内部函数,但不可以是一个分析函数 offset - 当前行之前/之后的偏移量. 没写的时候 default 为 1. default - 当超过 offset是的返回值. 没写的时候default 为 NULL.
举例
select EMPNO, EMPNAME, AGE, SALARY
from EMPINFO;
EMPNO EMPNAME AGE SALARY
1 王1 30 2000
2 于2 30 3000
3 王3 30 10000
4 于4 37 20000
5 王5 18 1000
6 于6 30 3000
7 孟1 38 9999
8 孟2 40 15000
9 王6 45 10000
10 于3 23 8000
1.lead函数
select t.*,lead(t.EMPNO,1,null) over(partition by t.AGE order by t.EMPNO) NUM
from empinfo t
EMPNO EMPNAME AGE SALARY NUM
5 王5 18 1000
10 于3 23 8000
1 王1 30 2000 2
2 于2 30 3000 3
3 王3 30 10000 6
6 于6 30 3000
4 于4 37 20000
7 孟1 38 9999
8 孟2 40 15000
9 王6 45 10000
2.lag函数
select t.*,lag(t.EMPNO,1,null) over(partition by t.AGE order by t.EMPNO) NUM
from empinfo t
EMPNO EMPNAME AGE SALARY NUM
5 王5 18 1000
10 于3 23 8000
1 王1 30 2000
2 于2 30 3000 1
3 王3 30 10000 2
6 于6 30 3000 3
4 于4 37 20000
7 孟1 38 9999
8 孟2 40 15000
9 王6 45 10000
用法:
■LAG (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
■LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
value_expression - 可以是表的一列,也可以是一个内部函数,但不可以是一个分析函数 offset - 当前行之前/之后的偏移量. 没写的时候 default 为 1. default - 当超过 offset是的返回值. 没写的时候default 为 NULL.
举例
select EMPNO, EMPNAME, AGE, SALARY
from EMPINFO;
EMPNO EMPNAME AGE SALARY
1 王1 30 2000
2 于2 30 3000
3 王3 30 10000
4 于4 37 20000
5 王5 18 1000
6 于6 30 3000
7 孟1 38 9999
8 孟2 40 15000
9 王6 45 10000
10 于3 23 8000
1.lead函数
select t.*,lead(t.EMPNO,1,null) over(partition by t.AGE order by t.EMPNO) NUM
from empinfo t
EMPNO EMPNAME AGE SALARY NUM
5 王5 18 1000
10 于3 23 8000
1 王1 30 2000 2
2 于2 30 3000 3
3 王3 30 10000 6
6 于6 30 3000
4 于4 37 20000
7 孟1 38 9999
8 孟2 40 15000
9 王6 45 10000
2.lag函数
select t.*,lag(t.EMPNO,1,null) over(partition by t.AGE order by t.EMPNO) NUM
from empinfo t
EMPNO EMPNAME AGE SALARY NUM
5 王5 18 1000
10 于3 23 8000
1 王1 30 2000
2 于2 30 3000 1
3 王3 30 10000 2
6 于6 30 3000 3
4 于4 37 20000
7 孟1 38 9999
8 孟2 40 15000
9 王6 45 10000
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26308209/viewspace-720909/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/26308209/viewspace-720909/