oracle sql語句實現累加 累減 累乘 累除

2021-05-24 07:53:12 字數 2777 閱讀 3797

在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,2);

insert into aspen values(1,4,5);

insert into aspen values(2,2,3);

insert into aspen values(2,3,5);

insert into aspen values(2,4,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,part_id,qnty,

sum(decode(rn,1,qnty,-qnty)) over(partition by parent_id order by part_id) running_prod

from (select parent_id,part_id,qnty,

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,part_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,part_id,

exp(sum(decode(rn,1,ln(qnty),-ln(qnty))) over(partition by parent_id order by part_id)) running_prod

from (select parent_id,part_id,qnty,

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

累乘和累除的缺陷是不能對負數進行運算 因為ln(負數)沒有意義

ORACLE sql語句實現累加 累減 累乘 累除

在oracle開發過程中經常會遇到累加 減 乘 除的問題。下面對這個做個小的總結 在此使用到 ln sum exp 來計算 sum 返回選擇的數值和總和 ln 返回x的自然對數.x必須是正數,並且大於0 exp 計算e的x次冪.e為自然對數,約等於2.71828.分解 首先理解 ln x ln x ...

oracle sql語句實現累加 累減 累乘 累除

在oracle開發過程中經常會遇到累加 減 乘 除的問題。下面對這個做個小的總結 建立測試表 create table test parent id number part id number quality number insert into test values 1,1,2 insert i...

常用oracle sql語句

建立表空間 alter tablespace nm offline drop tablespace nm including contents and datafiles drop user nmcascade create tablespace nm datafile 1 size 500m au...