A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @Zaran
Please check this query:
;WITH CTE1 AS
(
SELECT *,CASE WHEN DATEPART(weekday,E_AbsenceDate) = 6 THEN DATEADD(DAY,2,E_AbsenceDate) ELSE E_AbsenceDate END AS E_AbsenceDate_R
FROM test
),CTE2 AS
(
SELECT Id,caseid,S_AbsenceDate,E_AbsenceDate_R ,LEAD(S_AbsenceDate,1,DATEADD(DAY,2,E_AbsenceDate_R))OVER(PARTITION BY caseid ORDER BY S_AbsenceDate) AS LEAD_S_AbsenceDate
FROM CTE1
),CTE3 AS
(
SELECT *,CASE WHEN DATEDIFF(DAY,E_AbsenceDate_R,LEAD_S_AbsenceDate)>1 THEN 1 ELSE 0 END AS PART
FROM CTE2
),CTE4 AS
(
SELECT Id,caseid,S_AbsenceDate,E_AbsenceDate_R ,SUM(PART)OVER(ORDER BY caseid ASC,S_AbsenceDate DESC) AS PART
FROM CTE3
)
SELECT caseid,DATEDIFF(DAY,MIN(S_AbsenceDate),MAX(E_AbsenceDate_R))+1 AS CNT,MIN(S_AbsenceDate)AS S_AbsenceDate,MAX(E_AbsenceDate_R)AS E_AbsenceDate
FROM CTE4
GROUP BY caseid,PART
HAVING DATEDIFF(DAY,MIN(S_AbsenceDate),MAX(E_AbsenceDate_R))+1>=8
ORDER BY caseid,S_AbsenceDate
Output:
The final output is somewhat different from your desired result. Considering that March 5th and 6th are weekends, I think the absence date of F15 should be calculated from March 4th.
Best regards,
LiHong
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.