Sam
Sam

Reputation: 59

Running difference month over month

I have a sample data, i want to get the Difference in month over month data 'Lag' column for only row B

enter image description here

Upvotes: 0

Views: 113

Answers (1)

GMB
GMB

Reputation: 222572

If there always is just one row per month and id, then just use lag(). You can wrap this in a case expression so it only applies to id 'B'.

select 
    id,
    date,
    data,
    case when id = 'B' 
        then data - lag(data) over(partition by id order by date) 
    end lag_diff
from mytable

Upvotes: 1

Related Questions