Group rows by condition
12:20 19 Jan 2017

I have this data:

Start   End     Quantity
425     449     24
450     474     24
475     499     24
500     524     24
2300    2324    24
2400    2499    99
2500    2599    99
2800    2899    99
2900    2999    99
3200    3249    49
3250    3299    49
3300    3349    49
3350    3399    49
3400    3449    49
3500    3549    49
3600    3624    24
3650    3674    24
3700    3724    24
3950    3964    14
4000    4000    0
4150    4399    249
4400    4499    99
5034    5075    41

Quantity is a result of End - Start.

I would like to obtain the following data, the Generated rows:

Start   End     Quantity
425     449     24
450     474     24
475     499     24
500     524     24
425     524     96
2300    2324    24
2300    2324    24
2400    2499    99
2500    2599    99
-----GENERATED----
425     2599    438
------------------

2800    2899    99
2900    2999    99
3200    3249    49
3250    3299    49
3300    3349    49
3350    3399    49
3400    3449    49
3500    3549    49
-----GENERATED-----
2800    3549    492
------------------

3600    3624    24
3650    3674    24
3700    3724    24
3950    3964    14
4000    4000    0
4150    4399    249
4400    4499    99
5034    5075    41
-----GENERATED-----
3600    5075    475
------------------

The condition is that it has to sum all the quantities until 500. If it passes 500 do a new count.

I have tried with Rollup but I couldnt find the right condition to make it work.

Of course, this is way easier to do by programming code instead of SQL, but we must do it in database environment. The tools to get the generated rows can be anything, looping functions, new tables etc.

sql sql-server