Update date based on second highest date

Raj0125 511 Reputation points
2023-05-31T04:14:05.86+00:00

Hi,

I want to change the second highest Effective start date to current recored date where current indicator is 'Y'

Sample data as below.

User's image

I need to data as expected below after chnage the date.

User's image

Thank You

Azure SQL Database
SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. Anonymous
    2023-05-31T06:22:32.5266667+00:00

    Hi @Raj0125

    You can try this.

    create table test(
    R_Id int,
    Current_Indicator char(1),
    Deleted_Indicator char(1),
    Effective_Start_Date datetime,
    Effective_End_Date datetime,
    Inserted_Date datetime,
    Updated_Date datetime);
    
    insert into test values
    (3041888,'Y','N','2023-05-26 07:47:06','2099-12-31 00:00:00','2023-05-26 07:47:06','2023-05-26 07:47:06'),
    (3041888,'N','N','2021-03-31 02:05:17','2021-04-01 12:49:37','2021-03-31 02:05:17','2021-04-01 12:49:37'),
    (3041888,'N','N','2021-04-01 12:49:41','2023-05-26 07:47:02','2021-04-01 12:49:43','2023-05-26 07:47:02')
    
    ;with T1 as(
      select Effective_Start_Date as ESD,Effective_End_Date as EED,
             row_number()over(order by Effective_Start_Date) as num from test
    ),T2 as(
      select * from T1 where num = 2)
    update test set Effective_Start_Date = ESD,
                    Inserted_Date = ESD,
    				Updated_Date = ESD 
    from test as A cross join T2 as B where A.Current_Indicator = 'Y';
    
    select * from test;
    

    Output:

    User's image

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.