我有一张表:
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
想法?
答案 0 :(得分: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;