SQLite: accumulator (sum) column in a SELECT statement

后端 未结 3 1422
礼貌的吻别
礼貌的吻别 2020-12-28 20:16

I have a table like this one:

SELECT value FROM table;

value
1
3
13
1
5

I would like to add an accumul

3条回答
  •  无人及你
    2020-12-28 20:46

    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.

提交回复
热议问题