I have a User table similar to this:
| ID | DONATION | RANK |
| 4 | 10 | 12 |
| 9 | 20 | 8 |
| 2 | 40 | 5 |
| 3 | 80 | 2 |
I would like to construct a query where I retrieve the number of users where the combined sum of the donations is less than say 100, ordered by rank… something like (obviously not correct):
select count(*) where sum(donation) < 100 order by rank
Can’t figure out how to do this if it’s even possible. Not even sure I’m going about this the right way. Any ideas or pointers?
Assuming you have the following Donation table (as much as I think your ID column points to a user, I could not be sure):
The the following query will give you the number of users with their total donation < 100
Update based on extra information.
I do not believe you can get what you want from a single SQL statement, what you would need to do is create a cursor that loops around the records you want (in appropiate order) inserting the id into a temp table, and maintaining a total of the donations. When the total is above your limit, break out of the cursor loop and return the results. Something like this: