Código SQL:
Ver originalCREATE TABLE #temp
(
fecha datetime,
año INT,
mes INT,
dia INT,
laboral VARCHAR(20)
)
INSERT INTO #temp VALUES ('2013/08/01','2013',8,1,'SI' )
INSERT INTO #temp VALUES ('2013/08/02','2013',8,2,'SI')
INSERT INTO #temp VALUES ('2013/08/03','2013',8,3,'NO')
INSERT INTO #temp VALUES ('2013/08/04','2013',8,4,'NO')
INSERT INTO #temp VALUES ('2013/08/05','2013',8,5,'SI')
INSERT INTO #temp VALUES ('2013/08/06','2013',8,6,'SI')
INSERT INTO #temp VALUES ('2013/08/07','2013',8,7,'SI')
INSERT INTO #temp VALUES ('2013/08/08','2013',8,8,'SI')
INSERT INTO #temp VALUES ('2013/08/09','2013',8,9,'SI')
INSERT INTO #temp VALUES ('2013/08/09','2013',8,9,'NO')
CREATE TABLE #temp2
(
id INT,
fecha_creacion datetime,
fecha_cierre datetime,
dias INT
)
INSERT INTO #temp2 VALUES (1,'2013/08/01','2013/08/05',0)
INSERT INTO #temp2 VALUES (2,'2013/08/02','2013/08/08',0)
INSERT INTO #temp2 VALUES (3,'2013/08/01','2013/08/06',0)
INSERT INTO #temp2 VALUES (4,'2013/08/01','2013/08/09',0)
INSERT INTO #temp2 VALUES (5,'2013/08/01','2013/08/04',0)
INSERT INTO #temp2 VALUES (6,'2013/08/01','2013/08/03',0)
INSERT INTO #temp2 VALUES (7,'2013/08/01','2013/08/09',0)
DECLARE @dias INT
DECLARE @x INT
DECLARE @id INT
SET @x=1
SET @id=0
SELECT *,IDENTITY(INT,1,1) AS rn INTO #temp3 FROM #temp2
while @x<=(SELECT COUNT(*) FROM #temp3)
BEGIN
SELECT @id=id FROM #temp3 WHERE rn=@x
SELECT @dias=SUM(dias) FROM
(
SELECT CASE WHEN laboral='SI' THEN 1 END AS dias FROM #temp
WHERE fecha BETWEEN (SELECT fecha_creacion FROM #temp2 WHERE id=@x) AND (SELECT fecha_cierre FROM #temp2 WHERE id=@x)
) t1
UPDATE #temp2
SET dias=@dias
WHERE id=@x
SET @x=@x+1
END
DROP TABLE #temp3
SELECT * FROM #temp2
saludos!