Skip to content
Advertisement

Running total with condition and always looking at the previous value

I want to do a sequential sum in a table by taking into consideration a few extra conditions. We need to make sure that when the sum is taken sequentially so if a id has +40 then the next sum would be 130, if the next one is +1, the sum is still 130, now if the next one is -1 then the sum has to be 129. 100 needs to be added to the sum for the first time and from there on just the count should be added depending on condition. We need to even cap the min value of sum so it can’t be less than 70

I have tried the query below but it does not seem to look at the prior value.

Example that I tried:

Query tried:

I expect my output to look like:

Case1 Result:

Case2 Result:

Case3 Result:

Advertisement

Answer

THIS ANSWERS THE ORIGINAL VERSION OF THE QUESTION.

I think this does what you want:

I don’t understand where the 100 is coming from. It is not part of your explanation.

Here is a db<>fiddle that illustrates how this works using 30 as the limit (which seems to be your intention).

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