oracle中累計求和 oracle累計求和

2021-10-12 15:29:03 字數 1910 閱讀 2020

oracle累計求和

//將當前行某列的值與前面所有行的此列值相加,即累計求和:

//方法一:

with t as(

select 1 val from dual union all

select 3 from dual union all

select 5 from dual union all

select 7 from dual union all

select 9 from dual)

select val,

sum(val)

over (order by rownum rows between unbounded preceding and current row)

sum_val

from t

group by rownum,val

order by rownum;

val sum_val

1 13 4

5 97 16

9 25

//解析:

//sum(val)計算累積和;

//order by rownum 按照偽列rownum對查詢的記錄排序;

//between unbounded preceding and current row:定義了視窗的起點和終點;

//unbounded preceding:視窗的起點包括讀取到的所有行;

//current row:視窗的終點是當前行,預設值,可以省略;

//方法二:

with cte_1 as(

select 1 val from dual union all

select 3 from dual union all

select 5 from dual union all

select 7 from dual union all

select 9 from dual

,cte_2 as(

select rownum rn,val from cte_1

select a.val,sum(b.val) sum_val

from cte_2 a,cte_2 b

where b.rn <= a.rn

group by a.val

//方法三:

//建立乙個遞迴函式,求和

//f(n) = x + f(n-1)

create table t

asselect 1 id,1 val from dual union all

select 2,3 from dual union all

select 3,5 from dual union all

select 4,7 from dual union all

select 5,9 from dual

create or replace function fun_recursion(x in int)

return integer is

n integer :=0;

begin

select val into n

from t

where id=x;

if x=1 then

return n;

else

return n + fun_recursion(x-1);

end if;

exception

when others then

dbms_output.put_line(sqlerrm);

end fun_recursion;

select val,fun_recursion(id) sum_val from t;

val sum_val

1 13 4

5 97 16

9 25

參考文件

oracle中累計求和 oracle累計求和

poj2001 shortest prefixes trie樹應用 沉迷wow又頹了兩天orz,暴雪爸爸要在國服出月卡了.這是要我好好學習嗎?趕緊來刷題了.oj 題目大意是求所有字串裡每乙個字元 硬體相關 jtag介面 jtag joint test action group,聯合測試行動小組 是一...

Oracle按月份累計求和

原表 select to char reg date,yyyy mm regdate,count count from ep info t where 1 1 and t.reg date to date 2013 02 yyyy mm and t.reg date to date 2014 05 ...

oracle中關於生成累計和

首先建立oracle基礎表如下 現在要求分別累計各部門的工資之和 select empno,deptno,ename,sal,hiredate,sum sal over order by hiredate as totalsal from emp order by hiredate 效果如圖 當分析...