简体   繁体   中英

Dynamically add previous row value to current row value in SQL(Postgres)

I have a table with the following structure:

id col1 col2
1 1 0
2 1 1
3 1 0
4 1 2
5 1 1
6 1 2
7 1 1

I would like to get the following result:

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

where col3= col3 value of previous row + col1 value - col2 value

I added a column of zeroes like this:

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

and tried the following query:

select col1, col2, 
lag(col3) over (order by id) + col1 - col2 as col3
from t1;

However I am not able to obtain the desired result. I would like to get some help with this.

You just need analytical function sum as follows:

select col1, col2, 
       Sum(col1 - col2) over (order by id) as col3
  from t1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM