0

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.

2
  • 1
    SQL tables represent unordered sets. Without a column that specifies the ordering, there is no "previous" row or value. Commented Dec 31, 2020 at 15:25
  • there is an 'id' column, updated the question Commented Dec 31, 2020 at 15:33

1 Answer 1

1

You just need analytical function sum as follows:

select col1, col2, 
       Sum(col1 - col2) over (order by id) as col3
  from t1;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.