I have a query result with a total amount of hours scheduled per week in chronological order without gaps and have a set amount of hours that can be processed each week. Any hours not processed should be carried over to one or more following weeks. The following information is available.

```
Week | Hours | Capacity
1       2000     160
2        100     160
3          0     140
4        150     160
5        500     160
6       1500     160

```

Each week it should reduce the new hours plus carried over hours by the Capacity but never go below zero. A positive value should carry into the following week(s).

```
Week | Hours | Capacity | LeftOver = (Hours + LAG(LeftOver) - Capacity)
1        400     160          240 (400 +   0 - 160) 
2        100     160          180 (100 + 240 - 160)
3          0     140           40 (  0 + 180 - 140) 
4         20     160            0 ( 20 +  40 - 160) (no negative, change to zero)
5        500     160          340 (500 +   0 - 160)
6          0     160          180 (  0 + 340 - 160)

```

I'm assuming this can be done with cte recursion and a running value that doesn't go below zero but I can't find any specific examples of how this would be written.