SQLite: accumulator (sum) column in a SELECT statement

moala picture moala · Sep 24, 2010 · Viewed 18.6k times · Source

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

Answer

Sebastian Brózda picture Sebastian Brózda · Sep 24, 2010

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