我正在尝试创建一个表,根据某行的开始和结束日期计算多个日历。我有一张看起来像这样的表:
键Start_date End_date
123.1 1-10-2009 24-12-2009
123.2 1-7-2010 9-2-2011
123.3 1-5-2011 30-10-2011
.........
对于每个键,我想要一个新行,其中startdate为+1个月,直到enddate。
现在我的查询只有在我的临时表包含一行时才有效:
DECLARE @StartDate DATE = (select Start_date from #dim2);
SET DATEFIRST 7;
SET DATEFORMAT ymd;
SET LANGUAGE US_ENGLISH;
DECLARE @CutoffDate DATE = (select End_date from #dim2);
CREATE TABLE #dim3
([verwachte_aflossing] DATE,-- PRIMARY KEY,
);
INSERT #dim3([verwachte_aflossing] )
SELECT d
FROM
(
SELECT d = DATEADD(month, rn-1, @StartDate)
FROM
(
SELECT TOP (DATEDIFF(month, @StartDate, @CutoffDate))
rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
ORDER BY s1.[object_id]
) AS x
) AS y
现在有人如何处理这个问题?
答案 0 :(得分:0)
对于SQL Server递归 cte 是执行此操作的一个选项
WITH CTE as
(
select [Key], start_date, end_date from table
union all
select [Key], dateadd(month,1,start_date) start_date, end_date
from cte
where datediff(month, start_date, end_date) > 0
)
SELECT * FROM CTE
OPTION (MAXRECURSION 0)