开发者

Limit by running total in SQLite

开发者 https://www.devze.com 2023-01-21 13:16 出处:网络
Let\'s say I have a table like this (ordered by id): idamount ------ 110 215 310 430 I want a query which will return rows such that the sum of amount is greater than a given number. So (in a non-e

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消