Limit by running total in SQLite
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
select开发者_Python百科s 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:
select *
from YourTable t1
where 20 > coalesce(
(
select sum(amount)
from YourTable t2
where t2.id < t1.id
), 0)
The coalesce is to catch the first row, which has a sum of null
.
精彩评论