Otra solución, distinta de la de Libras:
Código SQL:
Ver originalIF Object_ID('tempdb..#T','U') IS NOT NULL DROP TABLE #T;
CREATE TABLE #T(ID INT PRIMARY KEY,
inicial DateTime,
final DateTime);
INSERT
INTO #T
VALUES (1,'20130701','20130705'),
(2,'20130706','20130710'),
(3,'20130703','20130705');
IF Object_ID('tempdb..#Nm','U') IS NOT NULL DROP TABLE #Nm;
WITH MinMax AS
(SELECT MIN(inicial) MinFecha,
MAX(final) MaxFecha
FROM #T),
Nm AS
(SELECT 1 N,
MinFecha Fecha
FROM MinMax
UNION ALL
SELECT Nm.N+1 N,
Nm.Fecha+1 Fecha
FROM Nm,
MinMax MM
WHERE Nm.Fecha<MM.MaxFecha)
SELECT *
INTO #Nm
FROM Nm;
DECLARE @SQL VARCHAR(MAX);
SELECT @SQL=IsNull(@SQL+','+CHAR(13),'')+CHAR(9)+CHAR(9)+'Max(Case When N='+CAST(N AS VARCHAR)+' Then ''*'' Else '''' End) ['+RIGHT('0'+CAST(N AS VARCHAR),2)+']'
FROM #Nm;
SET @SQL='Select ID,
Max(inicial) inicial,
Max(final) final,'+CHAR(13)+
@SQL+CHAR(13)+
'From #T
Inner Join #Nm
On #Nm.Fecha Between #T.inicial And #T.final
Group By ID;';
Print @SQL;
EXEC(@SQL);