I would be inclined to look at interval packing.Play with:-- *** Consumable Test Data ***-- Please provide in futureCREATE TABLE #t( EmployeeID int NOT NULL ,LoginDate date NOT NULL ,[status] varchar(10) NOT NULL);INSERT INTO #tVALUES (100, '20150110', 'Open') ,(100, '20150109', 'Open') ,(100, '20150108', 'Open') ,(100, '20150107', 'Closed') ,(100, '20150106', 'Pending') ,(100, '20150105', 'Open') ,(100, '20150104', 'Open');-- *** End Test Data ***WITH GrpsAS( SELECT EmployeeID, LoginDate, [status] ,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY LoginDate) - ROW_NUMBER() OVER (PARTITION BY EmployeeID, [status] ORDER BY LoginDate) AS Grp FROM #t),GrpDatesAS( SELECT EmployeeID, [status], Grp ,MIN(LoginDate) AS StartDate, MAX(LoginDate) AS EndDate FROM Grps GROUP BY EmployeeID, [status], Grp)SELECT TOP 1 EmployeeID, [status], StartDate, EndDate ,DATEDIFF(day, StartDate, EndDate) AS DaysOpenFROM GrpDatesWHERE [status] = 'open'ORDER BY StartDate DESC;