我需要帮助准备查询,该查询将根据开始日期时间和结束日期时间为我提供 30 分钟时段。
例如
在介于子句中的查询中,我将提供开始日期为 2024-11-13 00:00:00,结束日期为 2024-11-13 02:00:00。
查询结果应返回为:
开始时间结束时间
2018-03-12 00:00:00 2018-03-12 00:30:00 2018-03-12 00:30:00 2018-03-12 01:00:00 2018-03-12 01:00:00 2018-03-12 01:30:00 2018-03-12 01:30:00 2018-03-12 02:00:00
我没有测试,但你可以尝试这个方法:
WITH RECURSIVE time_slots AS (
-- Anchor member: Starting point of the time slots (provided start date)
SELECT
CAST('2024-11-13 00:00:00' AS DATETIME) AS starttime,
DATEADD(MINUTE, 30, CAST('2024-11-13 00:00:00' AS DATETIME)) AS endtime
UNION ALL
-- Recursive member: Add 30 minutes to each previous slot
SELECT
DATEADD(MINUTE, 30, starttime) AS starttime,
DATEADD(MINUTE, 30, endtime) AS endtime
FROM
time_slots
-- Stop recursion if the endtime exceeds the provided end date
WHERE
endtime < CAST('2024-11-13 02:00:00' AS DATETIME)
)
-- Select the generated time slots
SELECT starttime, endtime
FROM time_slots
ORDER BY starttime;