Search code examples
sqlsum

Counting SUM(VALUE) from previous cell


I have the following table:

A Sum(Tickets)
01-2022 5
02-2022 2
03-2022 8
04-2022 1
05-2022 3
06-2022 3
07-2022 4
08-2022 1
09-2022 5
10-2022 5
11-2022 3

I would like to create the following extra column 'TotalSum(Tickets)' but I am stuck....
Anyone who can help out?

A Sum(Tickets) TotalSum(Tickets)
01-2022 5 5
02-2022 2 7
03-2022 8 15
04-2022 1 16
05-2022 3 19
06-2022 3 22
07-2022 4 26
08-2022 1 27
09-2022 5 32
10-2022 5 37
11-2022 3 40

Solution

  • left join the same table where date is not bigger, then sum that for every date:

    select 
        table1.date, 
        sum(t.tickets) 
    from 
        table1 
            left join table1 t 
            on  t.date<= table1.date 
    group by
        table1.date;