Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite: accumulator (sum) column in a SELECT statement

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

like image 735
moala Avatar asked Sep 24 '10 10:09

moala


2 Answers

Here's a method to create a running total without the inefficiency of summing all prior rows. (I know this question is 6 years old but it's one of the first google entries for sqlite running total.)

create table t1 (value integer, accumulated integer, id integer primary key);
insert into t1 (value) values (1);
insert into t1 (value) values (3);
insert into t1 (value) values (13);
insert into t1 (value) values (1);
insert into t1 (value) values (5);

UPDATE
    t1
SET
    accumulated = ifnull(
    (
        SELECT
            ifnull(accumulated,0)
        FROM
            t1 ROWPRIOR
        WHERE
            ROWPRIOR.id = (t1.id -1 )),0) + value;


.headers on
select * from t1;
value|accumulated|id
1|1|1
3|4|2
13|17|3
1|18|4
5|23|5

This should only be run once after importing all the values. Or, set the accumulated column to all nulls before running again.

like image 82
TomWitt2 Avatar answered Oct 25 '22 01:10

TomWitt2


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

like image 33
Sebastian Brózda Avatar answered Oct 25 '22 02:10

Sebastian Brózda