递归累积函数 - 重复使用结果行作为输入
我尝试过数组、横向视图、递归视图、自定义函数、变量......我失去了希望。
我正在寻找一个可以从下表中产生“result_good”的函数。
“result_good”是“trx”和其自身之前的行的累积乘以“event”。
with t(id, trx, event, result_good) as
(values
(1, 20, 0.1, 2.000000),
(2,-10, 0.1, 1.200000),
(3, 20,-0.1,-3.320000),
(4,-10, 0.1, 1.988000),
(5, 20, 0.1, 4.186800),
(6,-10,-0.1,-3.605480),
(7, 20, 0.1, 5.244932)
)
-- non-recursive approximation of intended result
select *,
prev + event*sum(prev) over(
order by id range between unbounded preceding and 1 preceding
) as not_quite_my_tempo
from
(select t.*, event*sum(trx) over(order by id) as prev
from t
) t
order by id
x86_64-pc-linux-gnu 64 位上的 PostgreSQL 13.6
I have tried arrays, lateral views, recursive views, custom functions, variables... I'm losing hope.
I'm looking for a function that can produce "result_good" from the table below.
"result_good" is the accumulation of "trx" and previous rows from itself, multiplied by "event".
with t(id, trx, event, result_good) as
(values
(1, 20, 0.1, 2.000000),
(2,-10, 0.1, 1.200000),
(3, 20,-0.1,-3.320000),
(4,-10, 0.1, 1.988000),
(5, 20, 0.1, 4.186800),
(6,-10,-0.1,-3.605480),
(7, 20, 0.1, 5.244932)
)
-- non-recursive approximation of intended result
select *,
prev + event*sum(prev) over(
order by id range between unbounded preceding and 1 preceding
) as not_quite_my_tempo
from
(select t.*, event*sum(trx) over(order by id) as prev
from t
) t
order by id
PostgreSQL 13.6 on x86_64-pc-linux-gnu 64-bit
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
窗口函数不进行递归操作,并且递归 CTE 不允许在递归项中进行聚合。
每个结果都会递归地贡献给下一行。此函数写入临时表并重用结果:
db<>fiddle 此处< /a>
呼叫:
我将结果号码格式化为文本以匹配您想要的结果准确。您可能需要
数字
或双精度
。相应地进行调整。对于大型源表,性能将会恶化,因为下一行的成本不断增长。类似于 O(N²)。
小心地对所有查询中的列名称进行表限定,因为相同的名称可用于多种目的。
或者,递归函数也可以工作。示例:
A window function does not operate recursively, and recursive CTEs don't allow aggregation in the recursive term.
Each result contributes to the next row recursively. This function writes to a temp table and reuses results:
db<>fiddle here
Call:
I formatted the resulting number as text to match your desired result exactly. You may want a
numeric
ordouble precision
instead. Adapt accordingly.Performance will deteriorate for big source tables, as the cost for each next row keeps growing. Something like O(N²).
Carefully table-qualify column names in all queries as the same names are used for multiple purposes.
Alternatively, a recursive function could work. Example: