1. We have moved to a new forum! There may be a few things not working properly so please let us know if you find a bug. Remember to use the bbCode [ sql ] tag for SQL statements.

Create a third row that make the sum of past row + current row (i.e. a running sum)?

Discussion in 'SQL - Questions and Answers' started by alexfr, May 24, 2006.

  1. alexfr New Member

    Dialect: SQL 92
    EXAMPLE :
    WEEK TOTAL T
    ----------- ----------- -----------
    3 5 14
    2 6 8
    1 5 3
    0 3 0
  2. alexfr New Member

    Dialect: SQL 92
    SQL:
    SELECT T2.WEEK, T2.TOTAL, COALESCE(SUM(T1.TOTAL), 0) AS T
    FROM MY_TABLE T1
    LEFT OUTER JOIN MY_TABLE T2
    ON T1.WEEK < T2.WEEK
    GROUP BY T2.WEEK, T2.TOTAL
    ORDER BY 1 DESC


    Here I use the COALESCE function that will replace the NULL that can be found in some rows by 0 (otherwise the sum couldn't be done)
  3. alexfr New Member

    Dialect: SQL 99
    Nearly the same but last column is current total + previous like :
    week total t
    1 5 5
    2 6 11
    3 5 16
    SQL:

    select t2.week, t2.total, sum(t1.total)
    from MY_TABLE T1, MY_TABLE T2
    where T1.WEEK <=t2.week
    group by t2.week, T2.total
    order by t2.week asc
  4. delostilos Guest

    Dialect: SQL 99
    The following feature outside Core SQL-99 is used:

    T611, "Elementary OLAP operations"
    (checked with the mimer sql validator)
    SQL:

    SELECT week
    , total
    , sum(total) over (order by week desc) as running_total
    FROM my_table

Share This Page