SQLite: accumulator (sum) column in a SELECT statement

后端 未结 3 1400
礼貌的吻别
礼貌的吻别 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:43

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-28 20:59

    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

    0 讨论(0)
提交回复
热议问题