SQLite: accumulator (sum) column in a SELECT statement

佐手、 提交于 2019-11-29 01:24:07

问题


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


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3785995/sqlite-accumulator-sum-column-in-a-select-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!