使用postgresql中先前结果的累积来计算查询
Calculating a query with accumulation of the previous result in postgresql
我需要运行一个计算,必须考虑到他以前的结果并且有一个起始余额。
公式是上一个结果或初始结果 - 利润 + 贷款。在 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 中,您必须使用递归查询或函数来获取 当前查询 中的先前结果。这相当复杂,您可以使用称为 window 函数的聚合(在本例中为 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)
我需要运行一个计算,必须考虑到他以前的结果并且有一个起始余额。
公式是上一个结果或初始结果 - 利润 + 贷款。在 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 中,您必须使用递归查询或函数来获取 当前查询 中的先前结果。这相当复杂,您可以使用称为 window 函数的聚合(在本例中为 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)