0

我有一张像这样的桌子:

ID    MONTH     VALUE
1     06/2014    3
1     07/2014   -2
1     08/2014    1
2     03/2014    1
2     04/2014   -1
(...)

我想要的是创建一个新列,对值进行分层求和,例如:

ID    MONTH     VALUE    BALANCE
1     06/2014    3        3      <--  3 + "0" (no previous)
1     07/2014   -2        1      <-- -2 + 3   (previous balance plus current value)
1     08/2014    1        2      <--  1 + 1   (previous balance plus current value)
2     03/2014    1        1      <--  (...)
2     04/2014   -1
(...)

可能是在这里使用connect by子句的一种方式,只是无法理解它。

我正在使用 Oracle 11gR2

想法?

4

1 回答 1

1

分析函数sum (...) over (...)是完美的候选者:

create table tq84_t (
  id    number,
  month date,
  value number
);

insert into tq84_t values (1, date '2014-06-01',  3);
insert into tq84_t values (1, date '2014-07-01', -2);
insert into tq84_t values (1, date '2014-08-01', -1);

insert into tq84_t values (2, date '2014-03-01',  1);
insert into tq84_t values (2, date '2014-04-01', -1);


select
  id,
  month,
  value,
  sum(value) over (partition by id order by month) balance
from
  tq84_t;
于 2014-10-31T13:01:10.153 回答