我有一个开始日期和结束日期。我想获取这两个日期之间的日期列表。谁能帮助我指出查询中的错误。
id state start_date end_date
------------------------------------------------------------------------
2 New 2016-02-24 2016-02-28
2 Active 2016-02-28 2016-03-01
2 New 2016-03-01 NULL
3 New 2016-02-23 2016-02-25
3 Active 2016-02-25 2016-02-27
3 New 2016-02-27 NULL
id state start_date end_date
------------------------------------------------------------------------
2 New 2016-02-24 2016-02-25
2 New 2016-02-25 2016-02-26
2 New 2016-02-26 2016-02-27
2 New 2016-02-27 2016-02-28
2 Active 2016-02-28 2016-02-29
2 Active 2016-02-29 2016-03-01
2 New 2016-03-01 NULL
3 New 2016-02-23 2016-02-24
3 New 2016-02-24 2016-02-25
3 Active 2016-02-25 2016-02-26
3 Active 2016-02-26 2016-02-27
3 New 2016-02-27 NULL
答案 0 :(得分:3)
如果没有可用的日历表,可以尝试使用master..[spt_values]
进行以下查询,以生成缺少的日期。
;WITH cte
AS (SELECT ( Row_number()
OVER (
ORDER BY (SELECT NULL)) ) - 1 RN
FROM master..[spt_values] T1)
SELECT id,
state, Dateadd(day, rn, start_date) AS start_date,
Dateadd(day, rn + 1, start_date) AS end_date
FROM <Table_Name> t1
INNER JOIN cte T2
ON Dateadd(day, rn, start_date) < t1.end_date
注意:用适当的表名替换。
答案 1 :(得分:0)
如果您需要获取两个日期之间的所有日期,那么最简单的方法是使用递归公用表表达式(并且避免依赖未记录的系统表,这些表可能会更改而不会另行通知):
declare @start_date date = '2019-1-22';
declare @end_date date = '2019-1-29';
with GetDates As
(
select @start_date as TheDate
union all
select dateadd(day, 1, TheDate) from GetDates where TheDate < @end_date
)
select TheDate from GetDates;
现在,您可以将数据连接到递归CTE GetDates。