Postgres PL/pgSQL递归计算

3
也许有人能指引我正确的方向。我遇到了编写 PL/pgSQL 语句的问题,需要计算“计算”列,该列依赖于上个月的值。
最初我有 B 和 C 两列,需要计算“计算”列。
对于第4行,Excel 中的公式如下:=C4/(B4+OFFSET(D4;-1;0)) 月份 B C 计算 2012.02.01 1 15 13,20 2012.03.01 6 26 1,32 2012.04.01 8 21 2,29 2012.05.01 10 31 2,54 2012.06.01 11 10 0,72
也许有人有任何想法如何达到这一点。我知道 LAG 和 LEAD 函数,但那些只能引用“真实”的列,而不能引用计算本身。
注:这是样本数据和公式,真实数据要复杂得多。
如果有任何问题/想法,我将不胜感激。

你需要为此编写一个存储过程吗? - user330315
一种方法是通过 PL/SQL 函数将整个查询传递,该函数将计算附加列。另一种方法是构建自定义聚合函数。 - Ihor Romanchenko
1个回答

2

我认为你可以使用递归公共表达式

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

另一种方法是创建自己的自定义聚合函数。以下是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;

1
在大数据集上运行会非常缓慢。 - Ihor Romanchenko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接