Update row with value from previous row in a GROUP BY query in Postgres

Viewed 4968

Imagine I have a table like so:

account_id  date      value
1           1/1/2015  5
1           1/3/2015  7
1           1/7/2015  8
3           1/2/2015  4

What if I wanted to do an ORDER BY DATE and GROUP BY account_id and update each row with the value of the row before it?

So the end result should be:

account_id  date      value  prev_value
1           1/1/2015  5     null
1           1/3/2015  7     5
1           1/7/2015  8     7
3           1/2/2015  4     null

Any good way to do that in a single query?

1 Answers
Related