[英]Dynamically add previous row value to current row value in SQL(Postgres)
我有一个具有以下结构的表:
ID | col1 | col2 |
---|---|---|
1 | 1 | 0 |
2 | 1 | 1 |
3 | 1 | 0 |
4 | 1 | 2 |
5 | 1 | 1 |
6 | 1 | 2 |
7 | 1 | 1 |
我想得到以下结果:
ID | col1 | col2 | col3 |
---|---|---|---|
1 | 1 | 0 | 1 |
2 | 1 | 1 | 1 |
3 | 2 | 0 | 3 |
4 | 0 | 2 | 1 |
5 | 3 | 1 | 3 |
6 | 0 | 2 | 1 |
7 | 0 | 1 | 0 |
其中 col3= 前一行的 col3 值 + col1 值 - col2 值
我添加了一列这样的零:
ID | col1 | col2 | col3 |
---|---|---|---|
1 | 1 | 0 | 0 |
2 | 1 | 1 | 0 |
3 | 2 | 0 | 0 |
4 | 0 | 2 | 0 |
5 | 3 | 1 | 0 |
6 | 0 | 2 | 0 |
7 | 0 | 1 | 0 |
并尝试了以下查询:
select col1, col2,
lag(col3) over (order by id) + col1 - col2 as col3
from t1;
但是我无法获得预期的结果。 我想得到一些帮助。
您只需要分析 function sum
如下:
select col1, col2,
Sum(col1 - col2) over (order by id) as col3
from t1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.