![](/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.