0

I have a table like this:

| acct| month | total |
-------------------------------
| 123 | 02    | 100
| 123 | 03    | 100
| 123 | 04    | 100
| 123 | 06    | 100
| 123 | 07    | 100

I want to get a running total grouped by acct for each month. However as shown above the table does not have a record for month 5 (basically nothing changed in month 5), but I still want to create a row for month 5 that will be the same as the previous month 4 so that the result looks like:


| acct| month | total |
-------------------------------
| 123 | 02    | 100
| 123 | 03    | 200
| 123 | 04    | 300
| 123 | 05    | 300
| 123 | 06    | 400
| 123 | 07    | 500

Is there anyway to do this in Postgresql? I've explored using over and partition as described here Calculating Cumulative Sum in PostgreSQL but that is for the case where all months are present.

2
  • How does this add up to 600? There is only 500 in the original table. Commented Aug 17, 2018 at 22:38
  • woops, that's fixed now Commented Aug 17, 2018 at 22:46

1 Answer 1

2

Assuming you really want a cumulative sum with missing months, use generate_series() to generate the dates and then left join and a cumulative sum:

select t.acct, gs.mon, sum(total) over (order by mon)
from generate_series(2, 7, 1) gs(mon) left join
     t
     on gs.mon = t.mon;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.