我有一个表,其中每一行都有StartTime,EndTime和其他列的持续时间,例如:
Unique_ID SartTime EndTime Duration
1 08:00:00.0000000 12:00:00.0000000 10
我需要编写一个返回类似于:
的结果的查询Unique_ID SartTime EndTime Duration
1 08:00:00.0000000 08:10:00.0000000 10
1 08:10:00.0000000 08:20:00.0000000 10
1 08:20:00.0000000 08:30:00.0000000 10
and so on... till
1 11:50:00.0000000 12:00:00.0000000 10
提前致谢:)
答案 0 :(得分:1)
我更改了您的数据以显示持续时间可能不同,并且查询可以使用多行。我也改变它以缩短结果。
DECLARE @yourTable TABLE (Unique_ID INT, StartTime TIME, EndTime TIME, Duration INT);
INSERT INTO @yourTable
VALUES (1,'08:00:00.0000000','8:30:00.0000000',10),
(2,'06:00:00.0000000','7:00:00.0000000',30);
;WITH CTE_Recursion
AS
(
SELECT Unique_ID,
StartTime,
DATEADD(MINUTE,Duration,StartTime) NextTime,
EndTime,
Duration
FROM @yourTable
UNION ALL
SELECT Unique_ID, DATEADD(MINUTE,Duration,StartTime),DATEADD(MINUTE,Duration,NextTime),EndTime,Duration
FROM CTE_Recursion
WHERE DATEADD(MINUTE,Duration,StartTime) < EndTime
)
SELECT Unique_ID,StartTime,NextTime,Duration
FROM CTE_Recursion
ORDER BY Unique_ID,StartTime
结果:
Unique_ID StartTime NextTime Duration
----------- ---------------- ---------------- -----------
1 08:00:00.0000000 08:10:00.0000000 10
1 08:10:00.0000000 08:20:00.0000000 10
1 08:20:00.0000000 08:30:00.0000000 10
2 06:00:00.0000000 06:30:00.0000000 30
2 06:30:00.0000000 07:00:00.0000000 30
答案 1 :(得分:0)
如果您的DBMS不支持递归,您可以使用交叉连接到包含数字的表。我使用0到1439之间的值,因为一天有1440分钟,当然你应该根据你的数据减少这个值。这是纯粹的标准SQL:
SELECT Unique_ID
,StartTime + (n * INTERVAL '10' MINUTE)
,CASE
WHEN StartTime + ((n +1) * INTERVAL '10' MINUTE) < EndTime
THEN StartTime + ((n +1) * INTERVAL '10' MINUTE)
ELSE EndTime
end
FROM vt
CROSS JOIN
(SELECT n FROM number_table WHERE n BETWEEN 0 AND 1439) AS numbers
WHERE StartTime + (n * INTERVAL '10' MINUTE) >= StartTime
AND StartTime + (n * INTERVAL '10' MINUTE) < EndTime
ORDER BY 1,2