gpt4 book ai didi

postgresql - Postgres PL/pgSQL递归计算

转载 作者:行者123 更新时间:2023-11-29 12:21:52 25 4
gpt4 key购买 nike

也许有人能给我指出正确的方向。我在编写 PL/pgSQL 语句时遇到问题,我需要根据上个月的值计算“计算”列。

原来我有B列和C列,需要计算“计算”

Excel 中 4 行的公式如下所示:=C4/(B4+OFFSET(D4;-1;0))

Row  month          B       C       Calculation3    2012.02.01     1       15      13,204    2012.03.01     6       26      1,325    2012.04.01     8       21      2,296    2012.05.01     10      31      2,547    2012.06.01     11      10      0,72

也许有人知道如何实现这一点。我知道 LAG 和 LEAD 函数,但这些函数只能引用“真实”列而不是计算本身。

p.s 这是示例数据和公式,真正的要复杂得多。

如有任何问题/想法,我将不胜感激

最佳答案

嗯,我想你可以使用 RECURSIVE CTE :

with recursive CTE_R as 
(
select T.Row, T.month, T.B, T.C, 13.2 as Calculation
from temp as T
where T.Row = 3

union all

select T.Row, T.month, T.B, T.C, T.C / (T.B + C.Calculation) as Calculation
from CTE_R as C
inner join temp as T on T.Row = C.Row + 1
)
select *
from CTE_R

另一种方法是创建自己的 custom aggregate SQL FIDDLE EXAMPLE :

create function aggr_test_func(decimal(29, 10), int, int)
returns decimal(29, 10)
language SQL as
$func$
select $3 / ($2 + $1)
$func$;

create aggregate aggr_test (int, int)
(
sfunc = aggr_test_func,
stype = decimal(29, 10),
initcond = 0
);

select *, aggr_test(B, C) over (order by row asc) as Calculation
from test;

关于postgresql - Postgres PL/pgSQL递归计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17924080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com