简体   繁体   English

选择 sum(amt) 大于某个值的所有行

[英]Select all rows where sum(amt) greater than a value

I have a following table with Invoice and amt as columns我有一个以发票和 amt 为列的下表

+----------+------+
| Invoice  |  Amt | Ledger
+----------+------+
|        1 |    5 |  101
|        1 |    7 |  102
|        1 |   10 |  103
|        1 |    6 |  104
+----------+------+

I need to keep excluding the rows until sum(amt) <= value and fetch all the next rows.我需要继续排除行,直到 sum(amt) <= value 并获取所有下一行。

Suppose the value is 12假设值为 12

then output rows should be那么输出行应该是

+----------+------+
| Invoice  |  Amt |Ledger
+----------+------+
|        1 |   10 |103
|        1 |    6 |104
+----------+------+

Suppose the value is 11假设值为 11

then output rows should be那么输出行应该是

+----------+------+
| Invoice  |  Amt |Ledger
+----------+------+
|        1 |    7 |102
|        1 |   10 |103
|        1 |    6 |104
+----------+------+

Any help/suggestions will be appreciated.任何帮助/建议将不胜感激。

SQL tables represent unordered sets (technically multi-sets because duplicates are allowed), so I will assume that you have an ordering column. SQL 表表示无序集(技术上是多集,因为允许重复),所以我假设您有一个排序列。 What you care about is a cumulative sum.你关心的是累积和。 The rest is just filtering:剩下的只是过滤:

select t.*
from (select t.*,
             sum(amt) over (partition by invoice order by <ordering col>) as cumulative_amt
      from t
     ) t
where cumulative_amt >= 12;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM