lundi 1 juin 2020

t-sql loop through all rows and sum amount from column until value is reached

I have a table containing the below test data:

A table with userId, Name, Email and Amount of persons a table in restaurant is reserved for

I now would like to fill a restaurant with 12 seating spaces.

This should result in:

table result after selection

Basically, I need to loop from top to bottom through all rows and add the AmountPersons until I have filled the restaurant.

In this example:

(first few rows: AmountPersons) 3+1+2+4 = 10

UserId 52 can't be added because they reserved for 3 persons, which would result in 13 occupied places and there are only 12 available.

In the next row it notices a reservation for 1. This can be added to the previous 10 we already found.

NewTotal is now 11.

UserId 79 and 82 can't be added because we'd exceed the capacity again.

UserId 95 reserved for 1, this one can be added and we now have all places filled.

This is the result I get from the cursor I use, but I'm stuck now. Please help.

Temp_Result_Cursor

The while loop I have in the cursor basically stops when the next value would be higher than 12. But that is not correct.

Aucun commentaire:

Enregistrer un commentaire