lag(arg1,arg2,arg3):
arg2是希望检索的当前行分区的偏移量。是一个正的偏移量,时一个往回检索以前的行的数目。
arg3是在arg2表示的数目超出了分组的范围时返回的值。
在oracle开发过程中经常会遇到累加、减、乘、除的问题。
下面对这个做个小的总结
--创建测试表
create table aspen(parent_id number,part_id number,qnty number);
insert into aspen values(1,1,2);
insert into aspen values(1,2,3);
insert into aspen values(1,3,4,5);
insert into aspen values(2,3);
insert into aspen values(2,7);
--实现累加
select parent_id,part_id,qnty,
sum(qnty) over(partition by parent_id order by part_id) running_prod
from aspen
PARENT_ID PART_ID QNTY RUNNING_PROD
---------- ---------- ---------- ------------
1 1 2 2
1 2 3 5
1 3 2 7
1 4 5 12
2 2 3 3
2 3 5 8
2 4 7 15
--实现累减
select parent_id,
sum(decode(rn,-qnty)) over(partition by parent_id order by part_id) running_prod
from (select parent_id,
row_number() over(partition by parent_id order by part_id) rn
from aspen)
PARENT_ID PART_ID QNTY RUNNING_PROD
---------- ---------- ---------- ------------
1 1 2 2
1 2 3 -1
1 3 2 -3
1 4 5 -8
2 2 3 3
2 3 5 -2
2 4 7 -9
--实现累乘
select parent_id,
exp(sum(ln(qnty)) over(partition by parent_id order by part_id)) running_prod
from aspen
PARENT_ID PART_ID RUNNING_PROD
--------- ---------- ------------
1 1 2
1 2 6
1 3 12
1 4 60
2 2 3
2 3 15
2 4 105
--实现累除
select parent_id,
exp(sum(decode(rn,ln(qnty),-ln(qnty))) over(partition by parent_id order by part_id)) running_prod
from (select parent_id,
row_number() over(partition by parent_id order by part_id) rn
from aspen )
PARENT_ID PART_ID RUNNING_PROD
---------- ---------- ------------
1 1 2
1 2 .666666667
1 3 .333333333
1 4 .066666667
2 2 3
2 3 .6
2 4 .085714286
row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 和sum(qnty) over(partition by parent_id order by part_id)可实现累加,其余类似。