Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

Return Previous row value based on a condition

$
0
0
ProjIDClassIDSubClassIDStatusAmount            New Column
10111 Unrejected150           150-0=150
1012Unrejected200           200-0=200
10134  Unrejected100           100-0=100
10149   Approved5050
101510   Approved100100
101610   Approved125125
101714  Initiated150             150-125 =25
101822  Approved8080
101922  Approved4040
1011025   Initiated20              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 


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>