Skip to content
Advertisement

Update data based on the previous row in postgresql

For rn (row number) = 1, x and y always stays as 0. Now I need to update the rest of x and y columns based on the above scenario(IF ..ELSE). I am unable to update the next row without updating the previous row. Is there a way to do this in a query

Advertisement

Answer

You can use a recursive CTE for this type of query:

updates the table to


Note that the results are slightly different from your example from row “K” onward. I think "row J".x should be 7 not 0 (from the last else if condition), which changes the rest of the rows too. Still, I think it should be pretty easy to adapt the code to get the results you want.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement