创建一个包含开始日期和结束日期之间的日期的列表
Create a list with dates which are in between start and end dates
使用 SQL Server 2016。我有一个 table 具有不同的开始和结束日期
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
我现在想创建一个列表(存储在 table 变量中),其中包含每条记录的日期(从开始到结束以分钟为单位)。原来table可以有多条记录。
结果:
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;
请注意,这是 ANSI 语法。某些数据库可能不允许 recursive
关键字。日期算法因数据库而异。某些数据库可能会限制生成的行数,因此需要覆盖默认值。
编辑:
在 SQL 服务器中,这将是:
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);
使用 SQL Server 2016。我有一个 table 具有不同的开始和结束日期
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
我现在想创建一个列表(存储在 table 变量中),其中包含每条记录的日期(从开始到结束以分钟为单位)。原来table可以有多条记录。
结果:
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;
请注意,这是 ANSI 语法。某些数据库可能不允许 recursive
关键字。日期算法因数据库而异。某些数据库可能会限制生成的行数,因此需要覆盖默认值。
编辑:
在 SQL 服务器中,这将是:
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);