Skip to content
Advertisement

SQL compare the incremental difference from a column

Let’s say I have a table with the columns CurrentDateTime and CurrentValue where the CurrentValue column mostly increments. Sometimes though, the CurrentValue resets, this is where the issues start.

So, if it weren’t for the reset every now and then, I could just do this:

If the CurrentValue resets, the AccumulateValue is wrong.

Let’s say these are the values I got:

This would return 5

But if the values looks like this:

The result would be 101, and it should be 7.

I did try this (calculating the difference between each row and run SUM only on positive values):

This table is pretty large with small increments, and the SUM isn’t correct for some reason I can’t figure out. I noticed when comparing a month (with no reset), the value from this last query shows a higher value than the correct value.

Advertisement

Answer

First of all. Thanks for all the help I got.

Apparently, the table also had some corrupted data that made this somewhat messy. On top of that, the data could also decrease, wich I didn’t take into account.

Anyway, I needed to do some Changes to my code, but here it is:

It might look messy, but it returns the correct values.

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