表格如下
id a b c
1 12 19 0
2 15 17 0
5 11 32 0
6 18 79 0
3 23 342 0
4 134 545 0结果:
id a b c
1 12 19 0
2 15 17 228
5 11 32 81379
6 18 79 81731
3 23 342 483
4 134 545 8349
说明
ID=2的C列值为ID=1行的A*B+C
ID=3的C列值为ID=2行的A*B+C
ID=6的C列值为ID=5行的A*B+C
依次至最后一行
id a b c
1 12 19 0
2 15 17 0
5 11 32 0
6 18 79 0
3 23 342 0
4 134 545 0结果:
id a b c
1 12 19 0
2 15 17 228
5 11 32 81379
6 18 79 81731
3 23 342 483
4 134 545 8349
说明
ID=2的C列值为ID=1行的A*B+C
ID=3的C列值为ID=2行的A*B+C
ID=6的C列值为ID=5行的A*B+C
依次至最后一行
c4 = a3*b3+a2*b2+a1*b1;
如果写SQL语句会很复杂,不如用一个函数解决。
函数如下:
is
rs number;
a number;
b number;
begin
rs:=0;
(
select 1 id, 12 a, 19 b, 0 c from dual union all
select 2, 15 , 17 , 0 from dual union all
select 5, 11 , 32 , 0 from dual union all
select 6, 18 , 79 , 0 from dual union all
select 3, 23 , 342, 0 from dual union all
select 4, 134, 545, 0 from dual )select id,a,b,c,nvl(sum((a*b)) over( order by id rows between unbounded preceding and 1 preceding),0)
from t_test
select s.* from
(select * from abc where id=1
union all
select a.id,a.a,a.b,b.a*b.b+b.c c from abc a,
(select id,a,b,c from abc where id=1
union all
select m.id,m.a,m.b,n.d c from abc m,(select id,a*b d from abc) n where m.id=n.id+1) b
where a.id=b.id+1) s,
(select rownum rn,abc.* from abc) t
where s.id=t.id
order by rn;
create table abc(id number,a number,c number);--定义表结构create or replace type tj_type as object(id number,c number)--返回C列计算结果表类型
/create or replace type tj_tab_type as table of tj_type--返回C列的数据集合
/create or replace function tj_fun return tj_tab_type --返回C列值的函数
is
l_count number;
l_sum number:=0;
abc_tab tj_tab_type:=tj_tab_type();
begin
select count(*) into l_count from abc;
for i in 1..l_count
loop
select sum(s.c) into l_sum from (select id,c from abc where id=1
union all
select m.id,n.c from abc m,(select id,a*b c from abc) n where m.id=n.id+1
) s where s.id<=i;
--dbms_output.put_line(l_sum); --中间过程调试用
abc_tab.extend;
abc_tab(abc_tab.last):=tj_type(i,l_sum);
end loop;
return abc_tab;
end;select m.id,m.a,m.b,n.c from (select rownum rn,abc.* from abc) m,table(tj_fun) n where m.id=n.id;