correct dates based on id's

Suman Gupta 61 Reputation points
2023-01-06T16:13:55.34+00:00

Hi,
I have below data. I have to change the source to final result. My Date1 is messed up. Could you please help me with the query to achieve the Final result..
276984-image.png

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 125.7K Reputation points
    2023-01-06T17:11:36.21+00:00

    Check this statement:

    ;  
    with Q1 as  
    (  
        select *, row_number() over (order by UNQ_ID) i  
        from MessedTable  
    ),   
    Q2 as  
    (  
        select Q1.*, nd = case when p.Active_Flag = 0 then p.Date2 else '1/1/00' end  
        from Q1  
        left join Q1 p on p.i = Q1.i - 1  
    )  
    update Q2 set Date1 = nd  
    
    0 comments No comments

  2. Anonymous
    2023-01-09T02:06:20.117+00:00

    Hi @Suman Gupta

    You can try this query.

    ;with T1 as(  
      select *,row_number()over(order by ID2,UNQ_ID desc) as num from Source  
    ),T2 as(  
      select A.UNQ_ID,A.ID2,A.ID3,  
           case when B.Date2 = '12/31/99' or B.Date2 is null then A.Date1 else B.Date2 end as Date1,  
    	   A.Date2,A.Active_Flg  
      from T1 as A left outer join T1 as B on A.num = B.num - 1)  
    select * into Final_result from T2;  
    select * from Final_result;  
    

    Best regards,
    Percy Tang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. 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.

    0 comments No comments

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.