Let’s say I have a table like this (ordered by id):
id amount
--- ---
1 10
2 15
3 10
4 30
I want a query which will return rows such that the sum of amount is greater than a given number. So (in a non-existing syntax) SELECT id, amount LIMIT BY running_total(amount) 20 selects first 2 rows, ... LIMIT BY running_total(amount) 60 selects all rows. I can’t change the schema to keep the running total precomputed. Can this be done reasonably efficiently? It would be acceptable if the answer works only on SQLite.
You could use a subquery that sums all rows with a lower id:
The coalesce is to catch the first row, which has a sum of
null.