Below is an example of what I'm trying to achieve in a Redshift Database.
I have a variable current_value
and I want to create a new column value_desired
that is:
- the same as
current_value
if the previous row is null - equal to the last preceding non-null value if the previous row is non-null
It sounds like an easy task but I haven't found a way to do it yet.
row_numb current_value value_desired
1
2
3 47 47
4
5 45 45
6
7
8 42 42
9 41 42
10 40 42
11 39 42
12 38 42
13
14 36 36
15
16
17 33 33
18 32 33
I've tried with the LAG() function but I can only get the previous value (not the first in the "non-null" block), here is my take:
SELECT *
, CASE WHEN current_value is not null and LAG(current_value) is null THEN current_value
WHEN current_value is not null and LAG(current_value) is not null
THEN LAG(current_value)
ELSE NULL END AS value_desired
FROM test1
Any help is much appreciated, thanks.