If the user cannot have overlapping dates, this problem will be simple. First, for each entry, see how many months we have:
SELECT CustomerID, ABS(DATEDIFF('MONTH',StartDate,EndDate)) as Months FROM BaseData
Then we get max
SELECT CustomeID, MAX(Months) AS MaxContig FROM ( SELECT CustomerID, ABS(DATEDIFF('MONTH',StartDate,EndDate)) as Months FROM BaseData ) sub
Due to the popular demand here, how to do this with a recursive CTE - note that this code is based on the code above, so understand that before you dive. You also need to know how recursive CTEs work.
WITH rangeList AS ( SELECT CustomerID, StartDate, EndDate, DATEDIFF(month,StartDate,EndDate)+1 as Months FROM Customers UNION ALL SELECT R.CustomerID, R.StartDate, BD.EndDate, DATEDIFF(month,R.StartDate,BD.EndDate)+1 as Months FROM rangeList R JOIN Customers BD ON R.CustomerID = BD.CustomerID AND Month(DATEADD(month,1,R.EndDate)) = Month(BD.StartDate) AND Year(DATEADD(month,1,R.EndDate)) = Year(BD.StartDate) ) SELECT CustomerID, Max(Months) as MaxContig FROM rangeList GROUP BY CustomerID
Fiddle: http://sqlfiddle.com/#!6/eee59/14
Some notes about this solution.
- startdate should be before enddate (it could have been changed to fix this)
- dates should not overlap (this can be changed to fix this)
- you probably need to play around with the introduction, as it depends on your specifications ... as stated, this will not work if the start and end dates are in the same month - but maybe they should? However, remember to be careful, it is easy to have stackoverflow with infinite recursion.