Skip to content
Advertisement

Subtract value from previous value with exception

I have some calculations where a normal LAG function would solve it for me, which Ive tried. However. My question comes with an exception. Every january and july the value resets to 1500. On row nr 2 I need to subtract the value but with row nr 1 (this is where LAG comes in). This works but I dont know how to solve it with exception for july and then january again. See picture

enter image description here

Code I’ve worked with

After the answer below I tried

But I get error message that HOURS is not in an aggregate function nor GROUP BY. I added HOURS to GROUP BY but that obviously gives me rows per hour which is undesired

Advertisement

Answer

I put the months into groups and used a CTE to SUM for each group. Although Gordons answer is much simplier. Such as:

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