Skip to content
Advertisement

How to add and subtract value from previous rows based on condition

I have a table with values

I want to get values for RESULT column.

If Type is C then value gets subtracted from previous value, else if Type is P then value gets added to previous values.

This is what i’ve tried:

This is the Result that i have got

Advertisement

Answer

You need to implement a seft INNER JOIN to sum all values with Slno less than the current value, like below:

I think the biggest change you can make is to shift your mindset. When you think “previous values” you chose a procedural path which can be solved my any major programming language, but rapidly evolve to a cursor approach in SQL — what isn’t appropriate in this case.

When comes to SQL, you need to think in “sets”, so you can drive your efforts to identify those data sets and combine them.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement