Sql 创建一个日期介于开始日期和结束日期之间的列表
使用SQL Server 2016。我有一张有不同开始和结束日期的桌子Sql 创建一个日期介于开始日期和结束日期之间的列表,sql,date,while-loop,sql-server-2016,ssms-2016,Sql,Date,While Loop,Sql Server 2016,Ssms 2016,使用SQL Server 2016。我有一张有不同开始和结束日期的桌子 Start | End -----------------+----------------- 2018-01-01 00:00 | 2018-01-01 23:59 2018-01-12 05:33 | 2018-01-13 13:31 2018-01-24 22:00 | 2018-01-27 01:44 现在我想创建一个列表(存储在一个表变量中),其中包含每个记录的日期(从开始到结束以分
Start | End
-----------------+-----------------
2018-01-01 00:00 | 2018-01-01 23:59
2018-01-12 05:33 | 2018-01-13 13:31
2018-01-24 22:00 | 2018-01-27 01:44
现在我想创建一个列表(存储在一个表变量中),其中包含每个记录的日期(从开始到结束以分钟为单位)。原始表中可以有多条记录
结果:
2018-01-01 00:00 (1st row StartDate)
2018-01-01 00:01
2018-01-01 00:02
2018-01-01 00:03
... until
2018-01-01 23:59 (1st row EndDate)
followed by
2018-01-12 05:33 (2nd row StartDate)
2018-01-12 05:34
2018-01-12 05:35
2018-01-12 05:36
... until
2018-01-13 13:31 (2nd row EndDate)
and so on.
在ANSI标准SQL和许多数据库中,可以使用递归CTE:
with recursive cte as (
select datestart as dte, datestart, dateend
from t
union all
select dte + interval '1 minute', datestart, dateend
from cte
where dte < dateend
)
select dte
from cte
order by datestart, dateend, dte;
用您正在使用的数据库标记您的问题。@LukStorms。非常感谢。当我回答这个问题时,它没有数据库标签。
with cte as (
select datestart as dte, datestart, dateend
from t
union all
select dateadd(minut, 1, dte), datestart, dateend
from cte
where dte < dateend
)
select dte
from cte
order by datestart, dateend, dte
option (maxrecursion 0);