I want to update an row according to the values of two rows before the row how can i do that?
Let's assume my table looks like this
ID amount
1 1
2 3
7 5
And i want to do this
UPDATE amount
FROM table
SET amount = (AmounToFRowOneBefore + AmounToFRowTwoBefore)/2
WHERE ID=7;
Expected output would be
ID amount
1 1
2 3
7 2
And if I do this I don't know anything about the two rows before so no ID or anything is there a query to select the values before the selected row?
Best Answer
You can use either a window function:
Or use a subquery that returns the 2 previous rows:
Check them for performance.
db<>fiddle here