Search code examples
sqlpostgresqllag

how to get diff between subsequent rows without lag


I have

id value
1 12
1 15
1 17
1 22
1 22
1 23

And I need like this

id  value
1 --
1 3
1 2
1 5
1 0
1 1

Could you tell me, how to achive this?


Solution

  • You can try the below -

    select id, 
          value-max(value) over(order by id rows between 1 preceding and 1 preceding) as value
    from tablename