![](/img/trans.png)
[英]Postgres: Select all rows from array of objects where value >= x and also where no values are greater than x
[英]Select all rows where sum(amt) greater than a value
我有一个以发票和 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
+----------+------+
任何帮助/建议将不胜感激。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.