Los datos:
Código SQL:
Ver originalCREATE TABLE #T(id INT,
Fecha DateTime,
Estado VARCHAR(10));
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';
La recuperacion:
Código SQL:
Ver originalWITH T1 AS
(SELECT ROW_NUMBER() OVER(ORDER BY Fecha)-ROW_NUMBER() OVER(Partition BY Estado ORDER BY Fecha) N,
*
FROM #T),
T2 AS
(SELECT CASE Estado WHEN 'inicio' THEN N+1 ELSE N END N,
Estado,
CASE Estado WHEN 'inicio' THEN MIN(Fecha) ELSE MAX(Fecha) END Fecha
FROM T1
GROUP BY N,
Estado)
SELECT MIN(Fecha) inicio,
MAX(Fecha) Fin
FROM T2
GROUP BY N
ORDER BY N;