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 |
CodePudding user response:
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;
CodePudding user response:
You may use SUM() as a window function here:
SELECT A, SumTickets, SUM(SumTickets) OVER (ORDER BY A) AS TotalSumTickets
FROM yourTable
ORDER BY A;
But this assumes that you actually have a bona-fide column SumTickets which contains the sums. Assuming you really showed us the intermediate result of some aggregation query, you should use:
SELECT A, SUM(Tickets) AS SumTickets,
SUM(SUM(Tickets)) OVER (ORDER BY A) AS TotalSumTickets
FROM yourTable
GROUP BY A
ORDER BY A;
