0

I need to generate an increment field based on the difference bettwen current and previous value from another field:

enter image description here

So for example, this table would look like this:

enter image description here

I have this data in postgresql and my query is currently generating the table in first image, but I need it to create the second one.

Would be thankful for any hints.

1
  • 2
    We can't see the headers. What is C3 and what is C4? Commented Feb 6, 2020 at 14:55

2 Answers 2

2

I would recommend using lag():

select t.*,
       (totalreply -
        lag(totalreply, 1, totalreply) over (order by month)
       ) as incremental_totalreply
from t;

Note that this uses the 3-argument form of lag() so the first value is 0 rather than NULL.

Sign up to request clarification or add additional context in comments.

1 Comment

in fact, lag avoid to use negative offset. I only knew lead, but I'm here for learning, so thank you, upvoted.
1

You can use WINDOW FUNCTION, try this:

select month, totalread, (totalread - 
             lead(totalread, -1, totalread) over(order by totalread))    
from table1;

Reading doc, lead:

returns value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead return default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to null

1 Comment

Thank you! this helped a lot!

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.