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

前端 未结 5 1252
渐次进展
渐次进展 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:34

    If you have a version of SQLite that doesn't support OVER here is another approach using recursion against a group_concat string of rows.
    On SQLite version 3.22.0 2018-01-22 18:45:57 group_concat returns rows in database order. Create a common table expression and order it for different orders as in table work1 in the example.

    /* cumulative running total using group_concat and recursion
       adapted from https://blog.expensify.com/2015/09/25/the-simplest-sqlite-common-table-expression-tutorial/
    */
    
    WITH RECURSIVE work2 AS (
      SELECT NULL AS name, NULL AS gdppc, 0 AS cum, (select group_concat(name) from work1) AS gcname, (select group_concat(gdppc) from work1) AS gcgdppc 
      UNION
            SELECT
                CASE
                    WHEN INSTR(gcname, ',' )>0 THEN 
                        SUBSTR(gcname, 0, INSTR(gcname,','))
                    ELSE
                        gcname
                END,
                CASE
                    WHEN INSTR(gcgdppc, ',' )>0 THEN 
                        SUBSTR(gcgdppc, 0, INSTR(gcgdppc,','))
                    ELSE
                        gcgdppc
                END,
                CASE
                    WHEN INSTR(gcgdppc, ',' )>0 THEN 
                        cum + SUBSTR(gcgdppc, 0, INSTR(gcgdppc,','))
                    ELSE
                        cum + gcgdppc
                END,
                CASE
                    WHEN INSTR( gcname, ',' )>0 THEN 
                        SUBSTR( gcname, INSTR( gcname, ',' )+1 )
                    ELSE
                        NULL
                END,
                CASE
                    WHEN INSTR(gcgdppc, ',' )>0 THEN 
                        SUBSTR( gcgdppc, INSTR( gcgdppc, ',' )+1 )
                    ELSE
                        NULL
                END
            FROM work2
            WHERE gcgdppc IS NOT NULL
    
      ), 
    /* SQLite version 3.22.0 2018-01-22 18:45:57
       group_concat ignores ORDER BY when specified against the base table
       but does appear to follow the order of a common table expression 
    */
      work1 AS (select * from gdppc order by gdppc),
    
      gdppc AS (SELECT 'Burundi' AS name,399.657 AS gdppc
                UNION
                SELECT 'Democratic Republic of Congo', 329.645
                UNION
                SELECT 'Liberia',385.417
                UNION
                SELECT 'Zimbabwe',370.465)
    
    select name,gdppc,cum from work2 where name IS NOT NULL;
    /* result
    Democratic Republic of Congo|329.645|329.645
    Zimbabwe|370.465|700.11
    Liberia|385.417|1085.527
    Burundi|399.657|1485.184
    */
    

提交回复
热议问题