Skip to content
Advertisement

Running total of positive and negative numbers where the sum cannot go below zero

This is an SQL question.

I have a column of numbers which can be positive or negative, and I’m trying to figure out a way to have a running sum of the column, but where the total cannot go below zero.

I have tried a number of different window functions on this, but haven’t found a way to prevent the running total from going into negative numbers.

Any help would be greatly appreciated.


EDIT – Added a date column to indicate the ordering

Advertisement

Answer

Unfortunately, there is no way to do this without cycling through the records one-by-one. That, in turn, requires something like a recursive CTE.

I would recommend this approach only if your data is rather small. But then again, if you have to do this, there are not many alternatives other then going through the table row-by-agonizing-row.

Here is a db<>fiddle (using Postgres).

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