Hi @Raj0125
Only issue with Date sould not consider previous EffectiveEndDate when Rep_Id change.
Adding PARTITION BY
in the OVER
clause of LAG()
function would solve this issue.
The code is as below:
CREATE TABLE #Temp (Skey INT,Rep_Id int,Effective_Start_Date DATETIME,Effective_End_Date DATETIME)
INSERT INTO #Temp VALUES
(1,11,'2021-09-03 02:31:52','2021-09-05 02:30:54'),
(2,11,'2021-09-05 02:30:59','2021-09-07 02:31:38'),
(3,11,'2021-09-07 02:31:43','2021-09-08 02:51:14'),
(4,11,'2021-09-08 02:51:19','2021-09-14 02:38:53'),
(5,12,'2021-09-03 02:31:52','2021-09-05 02:30:54'),
(6,12,'2021-09-05 02:30:59','2021-09-07 02:31:38'),
(7,12,'2021-09-07 02:31:43','2021-09-08 02:51:14'),
(8,12,'2021-09-08 02:51:19','2021-09-14 02:38:53')
;WITH CTE AS
(
SELECT Skey,Effective_Start_Date,Effective_End_Date,
DATEADD(SECOND,4,LAG(Effective_End_Date)OVER(PARTITION BY Rep_Id ORDER BY Skey)) AS New_Effective_Start_Date
FROM #Temp
)
UPDATE CTE
SET Effective_Start_Date = New_Effective_Start_Date
Best regards,
Cosmog Hong
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".