我有一个以Invoice和amt为列的下表
+----------+------+
| Invoice | Amt | Ledger
+----------+------+
| 1 | 5 | 101
| 1 | 7 | 102
| 1 | 10 | 103
| 1 | 6 | 104
+----------+------+
我需要一直排除行,直到sum(amt)<= value并获取所有下一行。
假设值为12
则输出行应为
+----------+------+
| Invoice | Amt |Ledger
+----------+------+
| 1 | 10 |103
| 1 | 6 |104
+----------+------+
假设值是11
则输出行应为
+----------+------+
| Invoice | Amt |Ledger
+----------+------+
| 1 | 7 |102
| 1 | 10 |103
| 1 | 6 |104
+----------+------+
任何帮助/建议将不胜感激。
答案 0 :(得分:1)
SQL表表示无序集(技术上是多集,因为允许重复),所以我假设您有一个排序列。您所关心的是累计金额。剩下的只是过滤:
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;