I am trying to calculate a validtodate using the lead function. My data can change when a new file is uploaded. This file includes every location which is active in a warehouse.
ValidFromDate | ValidToDate | Location | AdministrationNr | WarehouseNr | FileName |
---|---|---|---|---|---|
2-1-2022 | 31-12-9999 | 19-26-2C | 1 | 22 | Locaties_Administratie_001_02-01-2022.txt |
11-10-2021 | 1-1-2022 | 19-26-2C | 1 | 22 | Locaties_Administratie_001_11-10-2021.txt |
24-8-2021 | 10-10-2021 | 19-26-2C | 1 | 22 | Locaties_Administratie_001_24-08-2021.txt |
4-5-2021 | 23-8-2021 | 19-26-2C | 1 | 22 | Locaties_Administratie_001_04-05-2021.txt |
15-6-2022 | 31-12-9999 | 21-48-4C | 1 | 22 | Locaties_Administratie_001_15-06-2022.txt |
4-1-2022 | 14-6-2022 | 21-48-4C | 1 | 22 | Locaties_Administratie_001_04-01-2022.txt |
2-1-2022 | 3-1-2022 | 21-48-4C | 1 | 22 | Locaties_Administratie_001_02-01-2022.txt |
11-10-2021 | 1-1-2022 | 21-48-4C | 1 | 22 | Locaties_Administratie_001_11-10-2021.txt |
24-8-2021 | 10-10-2021 | 21-48-4C | 1 | 22 | Locaties_Administratie_001_24-08-2021.txt |
4-5-2021 | 23-8-2021 | 21-48-4C | 1 | 22 | Locaties_Administratie_001_04-05-2021.txt |
15-6-2022 | 31-12-9999 | 21-60-3D | 1 | 22 | Locaties_Administratie_001_15-06-2022.txt |
4-1-2022 | 14-6-2022 | 21-60-3D | 1 | 22 | Locaties_Administratie_001_04-01-2022.txt |
2-1-2022 | 3-1-2022 | 21-60-3D | 1 | 22 | Locaties_Administratie_001_02-01-2022.txt |
11-10-2021 | 1-1-2022 | 21-60-3D | 1 | 22 | Locaties_Administratie_001_11-10-2021.txt |
24-8-2021 | 10-10-2021 | 21-60-3D | 1 | 22 | Locaties_Administratie_001_24-08-2021.txt |
4-5-2021 | 23-8-2021 | 21-60-3D | 1 | 22 | Locaties_Administratie_001_04-05-2021.txt |
Within this file a date is extracted, the ValidFromDate. Based on this date I want to find the next ValidFromDate to determine till what date this location was active. I did this with the following function:
LEAD( DATEADD(DAY, -1, [ValidFromDate]) ,1, '9999-12-31' )
OVER (PARTITION BY [AdministrationNr], [WarehouseNr], [Location]
ORDER BY [ValidFromDate] ASC ) as ValidToDate
However, when a location completely dissapears within the file this results in 9999-12-31. This is correct when the location is in the latest file because this is the active at this moment but this is also the case when a location dissapears in the warehouse.
In this case for location '19-26-2C' I have to find the next file date where it dit not appear in.
By checking whether a ValidFromDate is equal to the maximum date in all rows I can determine if the location is active at the current moment. See code:
CASE
WHEN ValidFromDate = MAX ( ValidFromDate ) OVER ( PARTITION BY WarehouseNr, AdministrationNr )
THEN '9999-31-12'
ELSE -- Next file date
All that is left for me is to fill the else statement with the next file date after file: 2022-01-02.
This is date 2022-01-04.
Is there any way for me to find this date?