Omega 2016-11-07
Oracle函数系列:
Oracle常见函数大全
Oracle-分析函数之连续求和sum(…) over(…)
Oracle-分析函数之排序值rank()和dense_rank()
Oracle-分析函数之排序后顺序号row_number()
Oracle-分析函数之取上下行数据lag()和lead()
lag()和lead()这两个函数是偏移量函数,可以查出一个字段的上一个值或者下一个值,配合over来使用。
lead函数,这个函数是向上偏移.
lag函数是向下偏移一位.
【语法】
lag(EXPR,<OFFSET>,<DEFAULT>)
LEAD(EXPR,<OFFSET>,<DEFAULT>)
【功能】表示根据COL1分组,在分组内部根据 COL2排序,而这个值就表示每组内部排序后的顺序编号(组内连续的唯一的)
lead () 下一个值 lag() 上一个值
【参数】
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;
数据规格:
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) ;