--Sample
SELECT CAST('6:00' as TIME) as BeginTime, 75 as Duration
INTO #Temp --drop table #Temp
UNION ALL
SELECT '7:00',45
UNION ALL
SELECT '7:15',45
UNION ALL
SELECT '7:45',60
UNION ALL
SELECT '8:00',60
UNION ALL
SELECT '9:00',90
--Query starts from here
DECLARE @MinTime TIME
SELECT @MinTime = MIN(BeginTime) FROM #Temp
DECLARE @MaxTime TIME
SELECT @MaxTime = MAX(BeginTime) FROM #Temp
;
WITH A(BeginTime, Duration)
AS
(
SELECT BeginTime, Duration FROM #Temp where BeginTime = @MinTime
UNION ALL
SELECT DATEADD(mi,A.Duration,A.BeginTime),B.Duration
FROM A
INNER JOIN #Temp as B
ON B.BeginTime = DATEADD(mi,A.Duration,A.BeginTime)
WHERE DATEADD(mi,A.Duration,A.BeginTime) < = @MaxTime
)
SELECT * FROM A
РЕДАКТИРОВАТЬ ОТВЕТ:
В этом случае все остальные BeginTime
бесполезны, все, что вам нужно подвести итог - это общее число Duration
с самым первым BeginTime
:
SELECT CAST('6:00' as TIME) as BeginTime, 75 as Duration, 1 as [Count]
INTO #Temp --drop table #Temp
UNION ALL
SELECT '7:00',45, 2
UNION ALL
SELECT '8:00',60, 3
UNION ALL
SELECT '9:00',90,4
UNION ALL
SELECT '10:00',60,5
UNION ALL
SELECT '11:00',30,6
DECLARE @MinTime Time
SELECT @MinTime = MIN(BeginTime) FROM #Temp
SELECT BeginTime,Duration FROM #Temp WHERE BeginTime = @MinTime
UNION ALL
SELECT DATEADD(MI,SUM(B.Duration), @MinTime) as BeginTime,
A.Duration
FROM #Temp as A
INNER JOIN #Temp as B
ON B.[Count] < A.[Count]
WHERE A.BeginTime != @MinTime
GROUP BY A.Duration, A.[Count]
ORDER BY BeginTime