I have a dataset for certain STS codes and I need to retain the Start and End Date When Status =03
I have the following Data
HAVE
ID CHGDATE STS
101 11/21/2022 00
101 11/22/2022 03
101 11/23/2022 03
101 11/24/2022 03
101 03/08/2023 04
102 08/05/2022 03
102 08/08/2022 04
102 11/10/2022 03
102 11/17/2022 00
WANT
ID STARTDATE ENDDATE
101 11/22/2022 03/08/2023
102 08/05/2022 08/08/2022
102 11/10/2022 11/17/2022
The ID 101 had
STS=03for the fist time on 11/22/2022, hence this should be my 'StartDatefor this Record. This record changed itsSTSto other than03on 3/8/2023, therefore this should beEndDateThe ID 102 had
STS=03multiple times with twoStartandEnddates 8/5-8/8 and 11/10-11/17My query SELECT ID,STS,CHGDATE AS STARTDATE, LEAD(CHGDATE) OVER (PARTITION BY ID ORDER BY CHGDATE) AS ENDDATE FROM HAVE WHERE STS=03
This query works for ID 102 but not for ID 101. Is there a different way to achieve the desired result?
Thanks
It won't work the way you're trying to do it. Your query is excluding all rows where sts <> '03'. I would split it into 2 derived tables, one for your start dates (sts = 03), and one for everything else (sts <> '03'). Then you can join those together, and use qualify to get only the relevant rows: