简体   繁体   中英

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

I have a following table with Invoice and amt as columns

+----------+------+
| 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.

Suppose the value is 12

then output rows should be

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

Suppose the value is 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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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