这两个函数是偏移量函数,可以查出一个字段的上一个值或者下一个值,配合over来使用。
lead函数,这个函数是向上偏移.
lag函数是向下偏移一位.
语法
【语法】
lag(EXPR,<OFFSET>,<DEFAULT>)
LEAD(EXPR,<OFFSET>,<DEFAULT>)
【功能】表示根据COL1分组,在分组内部根据 COL2排序,而这个值就表示每组内部排序后的顺序编号(组内连续的唯一的)
lead () 下一个值 lag() 上一个值
【参数】
- EXPR是从其他行返回的表达式
- OFFSET是缺省为1 的正数,表示相对行数。希望检索的当前行分区的偏移量
- DEFAULT是在OFFSET表示的数目超出了分组的范围时返回的值。
exp_str 是要做对比的字段
offset 是exp_str字段的偏移量 比如说 offset 为2 则 拿exp_str的第一行和第三行对比,第二行和第四行,依次类推,offset的默认值为1!
【说明】Oracle分析函数
栗子
create table LEAD_TABLE ( CASEID VARCHAR2(10), STEPID VARCHAR2(10), ACTIONDATE DATE ) insert into LEAD_TABLE values('Case1','Step1',to_date('20161101','yyyy-mm-dd')); insert into LEAD_TABLE values('Case1','Step2',to_date('20161102','yyyy-mm-dd')); insert into LEAD_TABLE values('Case1','Step3',to_date('20161103','yyyy-mm-dd')); insert into LEAD_TABLE values('Case1','Step4',to_date('20161104','yyyy-mm-dd')); insert into LEAD_TABLE values('Case1','Step5',to_date('20161105','yyyy-mm-dd')); insert into LEAD_TABLE values('Case1','Step4',to_date('20161106','yyyy-mm-dd')); insert into LEAD_TABLE values('Case1','Step6',to_date('20161107','yyyy-mm-dd')); insert into LEAD_TABLE values('Case1','Step1',to_date('20161201','yyyy-mm-dd')); insert into LEAD_TABLE values('Case2','Step2',to_date('20161202','yyyy-mm-dd')); insert into LEAD_TABLE values('Case2','Step3',to_date('20161203','yyyy-mm-dd')); commit;
数据规格:
输出当前 和 之前 之后的date 和 step
select a.caseid , a.stepid as currentStepID, a.actiondate as currentActionDate, lead(stepid) over(partition by a.caseid order by a.stepid) nextStep, lead(actiondate) over(partition by a.caseid order by a.stepid) nextActionDate, lag(stepid) over(partition by a.caseid order by a.stepid) preStep, lag(actiondate) over(partition by a.caseid order by a.stepid) preActionDate from lead_table a ;
进一步统计一下两者的相差天数
select caseid, stepid, actiondate, nextactiondate, nextactiondate - actiondate datebetween from (select caseid, stepid, actiondate, lead(stepid) over(partition by caseid order by actiondate) nextstepid, lead(actiondate) over(partition by caseid order by actiondate) nextactiondate, lag(stepid) over(partition by caseid order by actiondate) prestepid, lag(actiondate) over(partition by caseid order by actiondate) preactiondate from lead_table) ;