如何用 运行 总金额更新 postgres table
How do I update postgres table with a running total of amount
我正在使用 Postgres。我无法用总计 运行 更新 table:"Cum_sum"。
在 "cum_sum" 列中,我想用永久列 "Cum_sum" 更新 table。 "Cum_sum" 是 运行 总金额。
select 语句是有效的语句,但我无法更新 table,因为 UPDATE 不适用于 window 函数。
请协助。
SELECT cs3."Date",cs3."Amount",(sum("Amount") over (order by "Date")) as "Cum_sum" from cs3
cs3 Table
Date Amount Cum_sum
"2016-04-26" "10.00000" "10.00000"
"2016-06-01" "-10.00000" "0.00000"
"2018-01-23" "2150.57000" "2150.57000"
"2018-01-30" "-2150.57000" "0.00000"
我会在这里使用 data-modifying CTE(假设新添加的列 Balance
):
WITH balance (id, value) AS (
SELECT id, (sum("Amount") over (order by "Date", id)) FROM cs3
)
UPDATE cs3 SET "Balance" = balance.value FROM balance WHERE cs3.id = balance.id;
在线示例:https://dbfiddle.uk/?rdbms=postgres_11&fiddle=318929ea3bd4d029070558fe9b47f2a3
这也是@Jeremy 要求主键列的原因,因为我们需要确保正确关联更新值。
我正在使用 Postgres。我无法用总计 运行 更新 table:"Cum_sum"。
在 "cum_sum" 列中,我想用永久列 "Cum_sum" 更新 table。 "Cum_sum" 是 运行 总金额。
select 语句是有效的语句,但我无法更新 table,因为 UPDATE 不适用于 window 函数。
请协助。
SELECT cs3."Date",cs3."Amount",(sum("Amount") over (order by "Date")) as "Cum_sum" from cs3
cs3 Table
Date Amount Cum_sum
"2016-04-26" "10.00000" "10.00000"
"2016-06-01" "-10.00000" "0.00000"
"2018-01-23" "2150.57000" "2150.57000"
"2018-01-30" "-2150.57000" "0.00000"
我会在这里使用 data-modifying CTE(假设新添加的列 Balance
):
WITH balance (id, value) AS (
SELECT id, (sum("Amount") over (order by "Date", id)) FROM cs3
)
UPDATE cs3 SET "Balance" = balance.value FROM balance WHERE cs3.id = balance.id;
在线示例:https://dbfiddle.uk/?rdbms=postgres_11&fiddle=318929ea3bd4d029070558fe9b47f2a3
这也是@Jeremy 要求主键列的原因,因为我们需要确保正确关联更新值。