Teradata Retain value till next Change

152 Views Asked by At

I need to store the previous value in a column till there is a change and in case of change it would retain the new value

Example

Input
-------
ID Name Stdt        EndDt
1  A    20/01/2019  20/02/2019
1  B    20/02/2019  20/03/2019
1  C    20/03/2019  15/05/2019
1  C    15/05/2019  16/05/2019
1  C    16/05/2019  19/06/2019
1  C    19/06/2019  15/07/2019
1  A    15/07/2019  NULL


Output
----------
ID Name Stdt        EndDt       Previous Name
1  A    20/01/2019  20/02/2019  NULL
1  B    20/02/2019  20/03/2019  A
1  C    20/03/2019  15/05/2019  B
1  C    15/05/2019  16/05/2019  B
1  C    16/05/2019  19/06/2019  B
1  C    19/06/2019  15/07/2019  B
1  A    15/07/2019  NULL        C

Tried preceding and self joins but those are limited to know number of changes (like name can remain constant for N times) but need more dynamic

2

There are 2 best solutions below

0
On

You need nested Window functions:

SELECT ...
   -- assignt the previous value to all following rows
   Last_Value(CASE WHEN prev_name <> NAME THEN prev_name END IGNORE NULLS)
   Over (PARTITION BY id 
         ORDER BY stdt, enddt) as previous_name
FROM 
 ( 
   SELECT ...
      -- flag the changed row
      Lag(NAME) Over (PARTITION BY id ORDER BY stdt, enddt) AS prev_name

      -- pre-TD 16.10
      -- MIN(NAME) 
      -- Over (PARTITION BY id ORDER BY stdt, enddt
      --       ROWS BETWEEN 1 Preceding AND 1 Preceding) AS prev_name
   FROM mytable
 ) AS dt
0
On

thanks a lot for the solution it worked like a charm.

P.S : Sorry I was away on a vacation and the requirement changed a bit so didn't checked this solution provided.

Thanks again blessing us with your knowledge all the time :)

Regards Anindya