Se pone más y más complicado..
Supongo que en tal casos debemos omitir los 'fin' en el principio y los 'inicio' en el fin.
Te adjunto toda la solución con todos los datos:
Código SQL:
Ver originalIF Object_ID('tempdb..#T','U') IS NOT NULL DROP TABLE #T;
CREATE TABLE #T(id INT,
Fecha DateTime,
Estado VARCHAR(10));
INSERT INTO #T SELECT 1,'01-01-2013 01:00','fin';
INSERT INTO #T SELECT 1,'01-01-2013 02:00','fin';
INSERT INTO #T SELECT 1,'01-01-2013 03:00','fin';
INSERT INTO #T SELECT 1,'01-01-2013 08:00','inicio';
INSERT INTO #T SELECT 1,'01-01-2013 10:00','fin';
INSERT INTO #T SELECT 1,'01-01-2013 13:00','inicio';
INSERT INTO #T SELECT 1,'01-01-2013 13:30','fin';
INSERT INTO #T SELECT 1,'01-01-2013 13:40','fin';
INSERT INTO #T SELECT 1,'01-01-2013 14:00','inicio';
INSERT INTO #T SELECT 1,'01-01-2013 14:30','inicio';
INSERT INTO #T SELECT 1,'01-01-2013 15:40','fin';
INSERT INTO #T SELECT 1,'02-01-2013 14:00','inicio';
INSERT INTO #T SELECT 1,'02-01-2013 14:30','inicio';
INSERT INTO #T SELECT 1,'02-01-2013 14:40','inicio';
INSERT INTO #T SELECT 1,'02-01-2013 14:50','inicio';
INSERT INTO #T SELECT 1,'02-01-2013 15:30','fin';
INSERT INTO #T SELECT 1,'02-01-2013 15:33','fin';
INSERT INTO #T SELECT 1,'02-01-2013 15:35','fin';
INSERT INTO #T SELECT 1,'02-01-2013 15:40','fin';
INSERT INTO #T SELECT 1,'02-01-2013 23:00','inicio';
INSERT INTO #T SELECT 1,'02-01-2013 23:10','inicio';
INSERT INTO #T SELECT 1,'02-01-2013 23:20','inicio';
WITH T1 AS
(SELECT ROW_NUMBER() OVER(ORDER BY Fecha)-ROW_NUMBER() OVER(Partition BY Estado ORDER BY Fecha) N,
*
FROM #T),
T2 AS
(SELECT N,
Estado,
CASE Estado WHEN 'inicio' THEN MIN(Fecha) ELSE MAX(Fecha) END Fecha,
MIN(N) OVER() MinN,
MAX(N) OVER() MaxN
FROM T1
GROUP BY N,
Estado),
T3 AS
(SELECT ROW_NUMBER() OVER(Partition BY Estado ORDER BY Fecha) N,
Estado,
Fecha
FROM T2
WHERE NOT (N=MinN AND Estado='fin')
AND NOT (N=MaxN AND Estado='inicio'))
SELECT MIN(Fecha) inicio,
MAX(Fecha) Fin
FROM T3
GROUP BY N
ORDER BY N;