Click here to Skip to main content
15,880,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
need to calculate the value of indebtedness column so that when openingBalance !=0 then indebtedness = openingBalnce+SalesTotal-SalesReturn. But, when openingBalnce = 0 then indebtedness = indebtedness of the previous monthSales with the same SalesID. If the previous value = 0 get the previous value and continue get previous value till have value in this column:

SalesMonth SalesID  openingBalance  SalesTotal SalesReturn  Indebtednes
1         |  1    |     352200   |    0     |    5600     |   Null
1         |  2    |     50000    |   1100   |      0      |   Null
1         |  3    |     9500     |   6000   |      0      |   Null
2         |  1    |     0        |    0     |     1200    |   Null
2         |  2    |     0        |   300    |      0      |   Null
2         |  3    |     0        |   500    |     1000    |   Null
3         |  1    |     0        |    600   |      0      |   NULL
3         |  2    |     0        |   200    |      0      |   NULL
3         |  3    |    0         |     0    |       10    |   NULL
.
.
.
12           1             0          0           0              NULL
12           2             0          0           0              NULL
12           3             0          0           0              NULL



and the output like this:
SQL
when openingBalance !=0 then Indebtednes=openingBalnce+SalesTotal-SalesReturn
when openingBalnce =0 then Indebtednes=Indebtednes (of the previous
month of the same SalesID)+SalesTotal-SalesReturn.


SalesMonth SalesID  openingBalance  SalesTotal SalesReturn  Indebtednes
  1         |  1    |     352200   |    0     |    5600     |   346600
  1         |  2    |     50000    |   1100   |      0      |   51100
  1         |  3    |     9500     |   6000   |      0      |   15500
  2         |  1    |     0        |    0     |     1200    |   345400
  2         |  2    |     0        |   300    |      0      |   51400
  2         |  3    |     0        |   500    |     1000    |   15000
  3         |  1    |     0        |   600    |      0      |   346000
  3         |  2    |     0        |   200    |      0      |   51600
  3         |  3    |     0        |     0    |     10      |   14990
  .
  .
  .
  12           1             0          0           0              NULL
  12           2             0          0           0              NULL
  12           3             0          0           0              NULL
Posted
Updated 4-May-15 6:01am
v3

1 solution

You're looking for "running sum".

Have a look at past answers[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900