views:

120

answers:

2

Hi, I have a table like this one:

SELECT value FROM table;

value
1
3
13
1
5

I would like to add an accumulator column, so that I have this result:

value  accumulated
1      1
3      4
13     17
1      18
5      23

How can I do this? What's the real name of what I want to do? Thanks

+4  A: 

try this way:

select value,
(select sum(t2.value) from table t2 where t2.id <= t1.id ) as accumulated
from table t1

but if it will not work on your database, just add order by something

select value,
(select sum(t2.value) from table t2 where t2.id <= t1.id order by id ) as accumulated
from table t1
order by id

this works on an oracle ;) but it should on a sqlite too

Sebastian Brózda
Had it worked on a table without id for ordering (or ordering after another criterion, without possibility of strict < or unique <= comparison), I would have accepted this answer...
moala
You can do tthis with an analytic query when you use Oracle, no self joins needed, see http://www.orafaq.com/node/55. Sadly sqlte doesn't support analytical queries.
TTT
+1  A: 

The operation is called a running sum. SQLite does not support it as is, but there are ways to make it work. One is just as Sebastian Brózda posted. Another I detailed here in another question.

MPelletier
or "running total". Thx.
moala