Skip to content
Advertisement

SQL monthly rolling sum

I am trying to calculate monthly balances of bank accounts from the following postgresql table, containing transactions:

In “rolling sum” I mean that the sum should contain the sum of all transactions until the end of the given month from the beginning of time, not just all transactions in thegiven month.

I came up with the following query:

The problem is that this contains as many rows for each of the months for each banks as many transactions were there. If more, then more, if none, then none. I would like a query which contains exactly one row for each bank and month for the whole time interval including the first and last transaction.

How to do that?

An example dataset and a query can be found at https://rextester.com/WJP53830 , courtesy of @a_horse_with_no_name

Advertisement

Answer

You need to generate a list of months first, then you can outer join your transactions table to that list.

The cross join with all banks is necessary so that the all_years CTE will also contain a bank for each month row.

Online example: https://rextester.com/ZZBVM16426

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement