代码之家  ›  专栏  ›  技术社区  ›  Alexey Romanov

在sqlite中按运行总数限制

  •  1
  • Alexey Romanov  · 技术社区  · 15 年前

    假设我有一张这样的桌子 id ):

    id    amount
    ---   ---
    1     10
    2     15
    3     10
    4     30
    

    我需要一个查询,它将返回以下行: amount 大于给定的数字。所以(在不存在的语法中) SELECT id, amount LIMIT BY running_total(amount) 20 选择前2行, ... LIMIT BY running_total(amount) 60 选择所有行。我无法更改架构以保持预先计算的运行总数。这能合理有效地做到吗?如果答案仅在sqlite上有效,则可以接受。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Andomar    15 年前

    您可以使用一个子查询,该查询对ID较低的所有行求和:

    select  *
    from    YourTable t1
    where   20 > coalesce(
            (
            select  sum(amount)
            from    YourTable t2
            where   t2.id < t1.id
            ), 0)
    

    合并将捕获第一行,该行的和为 null .