Find number of days that intersect a given date range in a table of date ranges

I believe this might help you:

--create the table
SELECT 
    22484 LeaveID, 
    218 UserID, 
    CONVERT(DATETIME,'7/26/2019') StartDate, 
    CONVERT(DATETIME,'8/1/2019') EndDate, 
    7 Days
INTO #TblLeaveRequest

--Range Paramters
DECLARE @StartRange AS DATETIME = '8/1/2019'
DECLARE @EndRange AS DATETIME = '8/30/2019'

--Find sum of days between StartDate and EndDate that intersect the range paramters
--for UserId=218
SELECT 
    SUM(
    DATEDIFF(
        DAY
        ,CASE WHEN @StartRange < StartDate THEN StartDate ELSE @StartRange END
        ,DATEADD(DAY, 1, CASE WHEN @EndRange > EndDate THEN EndDate ELSE @EndRange END)
        )
    ) TotalDays
from #TblLeaveRequest
where UserId=218

This assumes that no start dates are greater than end dates. It also assumes that the range parameters always intersect some portion of the range in the table.

If the parameter ranges might not intersect then you’ll have to eliminate those cases by excluding negative days:

SELECT SUM( CASE WHEN Days < 0 THEN 0 ELSE Days END ) TotalDays
FROM
(
SELECT 
    DATEDIFF(
        DAY
        ,CASE WHEN @StartRange < StartDate THEN StartDate ELSE @StartRange END
        ,DATEADD(DAY, 1, CASE WHEN @EndRange > EndDate THEN EndDate ELSE @EndRange END)
        ) Days
from #TblLeaveRequest
where UserId=218
) TotalDays

Leave a Comment