我需要帮助准备查询,该查询将根据开始日期时间和结束日期时间为我提供 30 分钟时段。
例如
在介于子句之间的查询中,我将提供开始日期为
2024-11-13 00:00:00
和结束日期为 2024-11-13 02:00:00
。
查询结果应返回为:
****starttime endtime****
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,
DATE_ADD(CAST('2024-11-13 00:00:00' AS DATETIME), INTERVAL 30 MINUTE) AS endtime
UNION ALL
-- Recursive member: Add 30 minutes to each previous slot
SELECT
DATE_ADD(starttime, INTERVAL 30 MINUTE),
DATE_ADD(endtime, INTERVAL 30 MINUTE)
FROM
time_slots
-- Stop recursion if the endtime exceeds the provided end date
WHERE
endtime < '2024-11-13 02:00:00'
)
-- Select the generated time slots
SELECT starttime, endtime
FROM time_slots
ORDER BY starttime;
参考:https://sqlize.online/sql/mariadb115/ad0e87fbc2b8c8a01615acec7595a0f7/