Data looks like this
x
Row CurrentPrice PriceChangeDate PreviousPrice
1 7.9 25/03/2022 null
2 null 25/03/2022 null
3 7.9 24/03/2022 null
4 8 01/03/2022 8.5
5 8.5 24/02/2022 8
Expected Output
Row CurrentPrice PriceChangeDate PreviousPrice Difference
1 7.9 25/03/2022 7.9 0
2 7.9 24/03/2022 8 0.1
3 8 01/03/2022 8.5 0.5
4 8.5 24/02/2022 8 -0.5
I am not able to find a way to get the expected data.
Advertisement
Answer
Consider below approach
select *, round(PreviousPrice - CurrentPrice, 2) as Difference
from (
select * except(PreviousPrice),
ifnull(PreviousPrice, lag(CurrentPrice) over(order by PriceChangeDate)) as PreviousPrice
from your_table
where not CurrentPrice is null
)
if applied to sample data in y our question – output is