0

I have a following Records below...

+----+-------+------------+
| ID | token | actual_pay |
+----+-------+------------+
|  1 | 500   | 900        |
|  2 | 400   | 900        |
|  3 | 300   | 900        |
|  4 | 600   | 900        |
|  5 | 800   | 900        |
|  6 | 700   | 900        |
|  7 | 400   | 900        |
|  8 | 450   | 900        |
|  9 | 900   | 900        |
| 10 | 800   | 900        |
| 11 | 700   | 900        |
| 12 | 800   | 850        |
+----+-------+------------+

My problem is how to get the running total pay and running balance.
My formula are the following:
Legend:
RTP = Running Total Pay
BAL = Running Balance
TK = Token
PAY = Actual Pay

Formula:
1. On 1st ID, the value of TK must be default value of RTP, so the formula of BAL would be:
BAL=PAY-TK
2. While on the 2nd to the 12th ID, the formula would be:
RTP=BAL+PAY
BAL=RTP-TK

So the output will be like this one...

+----+-----+-----+------+------+
| ID | TK  | PAY | RTP  | BAL  |
+----+-----+-----+------+------+
|  1 | 500 | 900 | 500  | 400  |
|  2 | 400 | 900 | 1300 | 900  |
|  3 | 300 | 900 | 1800 | 1500 |
|  4 | 600 | 900 | 2400 | 1800 |
|  5 | 800 | 900 | 2700 | 1900 |
|  6 | 700 | 900 | 2800 | 2100 |
|  7 | 400 | 900 | 3000 | 2600 |
|  8 | 450 | 900 | 3500 | 3050 |
|  9 | 900 | 900 | 3950 | 3050 |
| 10 | 800 | 900 | 3950 | 3150 |
| 11 | 700 | 900 | 4050 | 3350 |
| 12 | 800 | 850 | 4200 | 3400 |
+----+-----+-----+------+------+
aynber
  • 22,380
  • 8
  • 50
  • 63
xdiver
  • 111
  • 1
  • 8

1 Answers1

0

I just copied and pasted your formula:

select id, token tk, actual_pay pay,
  if(@rtp is null, @rtp:=token, @rtp:=@bal+actual_pay) rtp,
  if(@bal is null, @bal:=actual_pay-token, @bal:=@rtp-token) bal
from records a
join (select @rtp:=null, @bal:=null) b
;

fiddle

Fabricator
  • 12,722
  • 2
  • 27
  • 40