| ProjID | ClassID | SubClassID | Status | Amount | New Column |
| 101 | 1 | 1 | Unrejected | 150 | 150-0=150 |
| 101 | 2 | 4 | Unrejected | 200 | 200-0=200 |
| 101 | 3 | 4 | Unrejected | 100 | 100-0=100 |
| 101 | 4 | 9 | Approved | 50 | 50 |
| 101 | 5 | 10 | Approved | 100 | 100 |
| 101 | 6 | 10 | Approved | 125 | 125 |
| 101 | 7 | 14 | Initiated | 150 | 150-125 =25 |
| 101 | 8 | 22 | Approved | 80 | 80 |
| 101 | 9 | 22 | Approved | 40 | 40 |
| 101 | 10 | 25 | Initiated | 20 | 20-40=-20 |
I have to calculate the new Amoutn column based on the status.The combination of projID,ClassId and SubClassId is unique.
For every row,based on status i should calculate the new amount.
FOr first row ,the Status ='Unrejected' so there is no previous row with Status='Approved' so the New amount=Amount-0=Amount
Same for second,Third row.
For fourth row the Status='Approved' So retain the amount in new AMount column.
same for fifth and sixth row.
For seventh row ,the status='Initiated' so calculate the new amount column based on the previous approved row which is (projid=101,classid=6 and subclassid=10) where the amount=125.So the current row should have values AMount-(previous amount with Status Approved=125)=25.
for Eighth and ninth retain amount in new column as Status='Approved'
for tenth row,the status='Initiated' so calculate the new amount column based on the previous approved row which is (projid=101,classid=9 and subclassid=22) where the amount=40.So the current row should have values AMount(20)-(previous amount with Status Approved=40)=-20.
CREATE TABLE sampleData (ProjectID VARCHAR(50),ClassID INT,SubClassID INT,Status VARCHAR(50),Amount INT)INSERT INTO sampleDataSELECT '101', 1, 1, 'Unrejected', 150UNIONSELECT '101', 2, 4, 'Unrejected', 200UNIONSELECT '101', 3, 4, 'Unrejected', 100UNIONSELECT '101', 4, 9, 'Approved', 50UNIONSELECT '101', 5, 10, 'Approved', 100UNIONSELECT '101', 6, 10, 'Approved', 125UNIONSELECT '101', 7, 14, 'Initiated', 150UNIONSELECT '101', 8, 22, 'Approved', 80UNIONSELECT '101', 9, 22, 'Approved', 40UNIONSELECT '101', 10, 25, 'Initiated', 20