SQL Server 2014查询 - Windows
我有记录,其中开始和结束时间跨越多个30分钟的间隔。我希望结果每隔30分钟有一个单独的行。因此,当开始时间是2:01:37而结束时间是05:00:21时,我希望看到以下间隔的行:02:00:00,02:30:00,03:00:00 ,03:03:00,04:00:00,04:30:00,05:00:00我希望看到显示每行的开始和结束时间,以便我可以进行计算以确定每个间隔的经过时间。对于大多数这些时间间隔,以秒为单位的经过时间将为1800.第一个和最后一个时间间隔将更短。
我已经尝试了一些链接,并没有找到我想要的东西。我感谢您提供的任何帮助。
答案 0 :(得分:0)
使用递归CTE生成间隔。您可以按照以下示例:
IF OBJECT_ID('tempdb..#SuppliedIntervals') IS NOT NULL
DROP TABLE #SuppliedIntervals
CREATE TABLE #SuppliedIntervals (
StartInterval DATETIME,
EndInterval DATETIME)
INSERT INTO #SuppliedIntervals (
StartInterval,
EndInterval)
VALUES
('2018-04-22 02:00:00.000', '2018-04-22 05:00:00.000'),
('2018-04-22 19:30:00.000', '2018-04-22 20:30:00.000')
;WITH RecursiveIntervalCTE AS
(
SELECT
T.StartInterval,
T.EndInterval,
GeneratedInterval = T.StartInterval
FROM
#SuppliedIntervals AS T
UNION ALL
SELECT
R.StartInterval,
R.EndInterval,
GeneratedInterval = DATEADD(MINUTE, 30, R.GeneratedInterval)
FROM
RecursiveIntervalCTE AS R
WHERE
DATEADD(MINUTE, 30, R.GeneratedInterval) <= R.EndInterval
)
SELECT
*
FROM
RecursiveIntervalCTE AS R
ORDER BY
R.StartInterval,
R.GeneratedInterval
/*
Results:
StartInterval EndInterval GeneratedInterval
----------------------- ----------------------- -----------------------
2018-04-22 02:00:00.000 2018-04-22 05:00:00.000 2018-04-22 02:00:00.000
2018-04-22 02:00:00.000 2018-04-22 05:00:00.000 2018-04-22 02:30:00.000
2018-04-22 02:00:00.000 2018-04-22 05:00:00.000 2018-04-22 03:00:00.000
2018-04-22 02:00:00.000 2018-04-22 05:00:00.000 2018-04-22 03:30:00.000
2018-04-22 02:00:00.000 2018-04-22 05:00:00.000 2018-04-22 04:00:00.000
2018-04-22 02:00:00.000 2018-04-22 05:00:00.000 2018-04-22 04:30:00.000
2018-04-22 02:00:00.000 2018-04-22 05:00:00.000 2018-04-22 05:00:00.000
2018-04-22 19:30:00.000 2018-04-22 20:30:00.000 2018-04-22 19:30:00.000
2018-04-22 19:30:00.000 2018-04-22 20:30:00.000 2018-04-22 20:00:00.000
2018-04-22 19:30:00.000 2018-04-22 20:30:00.000 2018-04-22 20:30:00.000
*/