Search code examples
sqlsql-serverdateadddatahistory

Creating a column that'll show previous rates


I'm creating a column that will show an old address. Whenever an address is updated the old address is expired the day before the new one is supposed to take effect and a new row with the same account number will be added with the new address (ex: old address will show: From: 10/01/2020 To: 12/31/2021 and the new address From: 01/01/2022 To: 12-31-9999). I'm trying to show old and new address side by side for each account number in SQL, but I'm getting zeros.

Sample Data

AccountNumber Address ValidFrom ValidTo
4895626 720 Main 10/01/2020 12/31/2021
9794651 158 4th St 09/29/2002 12/19/2020
4895626 5986 9th Ave 01/01/2022 12/31/9999

Desired Results

AccountNumber Address ValidFrom ValidTo PreviousAddress
4895626 720 Main 10/01/2020 12/31/2021 0
9794651 158 4th St 09/29/2002 12/19/2020 0
4895626 5986 9th Ave 01/01/2022 12/31/9999 720 Main
DECLARE @PreviousValidTo DATE;
SELECT @PreviousValidTo = DATEADD(DAY, -1, Z.ValidFrom)
FROM Address.NewAddress Z
SELECT Address, ValidFrom, ValidTo
CASE
            WHEN @PreviousValidTo = C.ValidFrom
            THEN C.Address
            ELSE 0
            END AS PreviousAddress
FROM Address.NewAddress C

Solution

  • Possibly you could use lag

    select *,
      Lag(address,1,'0') over(partition by accountnumber order by validto) PreviousAddress
    from address.NewAddress