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

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

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

5条回答
  •  旧时难觅i
    2021-02-05 15:31

    As of SQLite 3.25.0, since 2018-09-15, window functions and their keyword OVER are supported. The answer to your question is now easy:

    SELECT Country, Gdp, SUM(Gdp) OVER (ROWS UNBOUNDED PRECEDING)
    FROM CountryGdp;
    

    This is the minimal query that does what you request, but it doesn't define any ordering so here is a more proper way of doing it.

    SELECT
        Country,
        Gdp,
        SUM(Gdp) OVER (
            ORDER BY Country -- Window ordering (not necessarily the same as result ordering!)
            ROWS BETWEEN -- Window for the SUM includes these rows:
                UNBOUNDED PRECEDING -- all rows before current one in window ordering
                AND CURRENT ROW -- up to and including current row.
            ) AS RunningTotal
    FROM CountryGdp
    ORDER BY Country;
    

    In any way, the query should run in O(N) time.

提交回复
热议问题