I have the following table:
/**
| NAME | DELTA (PAID - EXPECTED) | PERIOD |
|-------|-------------------------|--------|
| SMITH | -50| 1|
| SMITH | 0| 2|
| SMITH | 150| 3|
| SMITH | -200| 4|
| DOE | 300| 1|
| DOE | 0| 2|
| DOE | -200| 3|
| DOE | -200| 4|
**/
DROP TABLE delete_me;
CREATE TABLE delete_me (
"NAME" varchar(255),
"DELTA (PAID - EXPECTED)" numeric(15,2),
"PERIOD" Int
);
INSERT INTO delete_me("NAME", "DELTA (PAID - EXPECTED)", "PERIOD")
VALUES
('SMITH', -50, 1),
('SMITH', 0, 2),
('SMITH', 150, 3),
('SMITH', -200, 4),
('DOE', 300, 1),
('DOE', 0, 2),
('DOE', -200, 3),
('DOE', -200, 4)
Where period represents time, with 1 being the newest and 4 being the oldest. In each time period the person was charged and amount and they could pay off that amount or more. A negative delta means that they owe for that time period. A positive delta means that they paid over the expected amount and has a credit for that time period that can be applied to other time periods. If there's a credit we'd want to pay off the oldest time period first. I want to get how much unpaid debt is still looming for each time period.
So in the example above I'd want to see:
| NAME | DELTA (PAID - EXPECTED) | PERIOD | PERIOD BALANCE |
|-------|-------------------------|--------|----------------|
| SMITH | -50| 1| -50|
| SMITH | 0| 2| 0|
| SMITH | 150| 3| 0|
| SMITH | -200| 4| -50|
| DOE | 300| 1| 0|
| DOE | 0| 2| 0|
| DOE | -200| 3| -100|
| DOE | -200| 4| 0|
How can I use Postgres SQL to show the Unpaid debt within periods?
Additional description: for doe initially, in the oldest period, 200 was owed, the next period the owed the original 200 plus another 200 (400 total owed). In Period 2 the monthly charge was paid, but not the past balances. In the most recent period (1) 300 over the monthly amount was paid (200 of this was applied to the oldest debt in period 4, meaning it was paid off; leaving 100 to apply to period three's debt; and after applying the remaining 100, 100 was still owed).
For the Smith family initially in period 4 they underpaid 200. The next period they overpaid 150 for the month and this was applied to the oldest debt of 200, leaving 50 to still be paid. In period 2 the monthly bill was paid exactly, they still owed the 50 dollars from period 4. Then in period 1 they underpaid 50. They owe 100 in total, 50 for period 1 and 50 for period 4.