Skip to content
Advertisement

Compute a Decreasing Cumulative Sum in SQL Server

What I’m trying to achieve is a cumulative sum on a non-negative column where it decreases by 1 on every row, however the result must also be non-negative.

For example, for the following table, summing over the “VALUE” column ordered by the “ID” column:

I expect:

Advertisement

Answer

Your question is not very well described. My best interpretation is that you want to count down from positive value, starting over when you hit the next one.

You can define the groups with a cumulative sum of the non-zero values. Then use a cumulative sum on the groups:

Here is a db<>fiddle.

EDIT:

It strikes me that you might want to keep all the “positive” values and count down — remembering if they don’t go down to zero. Alas, I think the simplest method is a recursive CTE in this case:

The db<>fiddle has both solutions.

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