How do I calculate a running SUM on a SQLite query?

前端 未结 5 1241
渐次进展
渐次进展 2021-02-05 14:42

How do I get a column that is the sum of all the values before of another column?

5条回答
  •  臣服心动
    2021-02-05 15:13

    Cross join solutions like Diomidis Spinellis suggested take O(N^2) time. A recursive CTE can work faster, if you can stomach the convoluted code.

    This produces the same output as his.

    WITH RECURSIVE running(id, name, gdppc, rt) AS (
        SELECT row1._rowid_, row1.name, row1.gdppc, COALESCE(row1.gdppc,0)
        FROM gdppc AS row1
        WHERE row1._rowid_ = (
            SELECT a._rowid_
            FROM gdppc AS a
            ORDER BY a.gdppc, a.name, a._rowid_
            LIMIT 1)
        UNION ALL
        SELECT row_n._rowid_, row_n.name, row_n.gdppc, COALESCE(row_n.gdppc,0)+running.rt
        FROM gdppc AS row_n INNER JOIN running
        ON row_n._rowid_ = (
            SELECT a._rowid_
            FROM gdppc AS a
            WHERE (a.gdppc, a.name, a._rowid_) > (running.gdppc, running.name, running.id)
            ORDER BY a.gdppc, a.name, a._rowid_
            LIMIT 1))
    SELECT running.name, running.gdppc, running.rt
    FROM running;
    

    Ordering and comparisons take care of duplicates, COALESCE is there to ignore NULLs.

    If you have a good index, this should be O(N log N). Since SQLite doesn't support cursors, an O(N) solution probably doesn't exist without relying on an external application.

提交回复
热议问题