用postgresql中的先前结果的累积来计算查询

我需要进行计算,必须考虑到他以前的结果,并有一个初始平衡。

该公式为PREVIOUS RESULT或INITIAL IF FIRST – profit + loans。 在Excel中这很容易:

1- A1=Initial 2- A2=A1 - B2:profit + C2:loans 3- A3=A2 - B3:profit + C3:loans 4- A4=A3 - B4:profit + C4:loans 

但如何与SQL?

在SQL中,您必须使用recursion查询或函数来获取当前查询中的先前结果 。 这是相当复杂的,而不是这个,你可以使用一个集合(在这种情况下sum() )被称为窗口函数,这也被称为累积聚合

示例设置:

 create table my_table(id serial primary key, val int, profit int, loans int); insert into my_table values (val, profit, loans) (100, null, null), (null, 10, 20), (null, 20, 10), (null, 40, 30); 

查询:

 select id, sum(val) over w + sum(-coalesce(profit, 0)+ coalesce(loans, 0)) over w as val, profit, loans from my_table window w as (order by id) order by id; id | val | profit | loans ----+-----+--------+------- 1 | 100 | | 2 | 110 | 10 | 20 3 | 100 | 20 | 10 4 | 90 | 40 | 30 (4 rows)