T-SQL从日期范围获得数月

时间:2012-08-29 17:18:57

标签: tsql

我有一个包含id和开始日期和结束日期的表。我希望插入到另一个表中,每月结束于开始数据和结束日期之间以及ID,例如

ID  Start Date  End Date
1   2012-01-01  2012-03-31
2   2012-10-01  2012-12-31

结果

ID  MONTH END
1   2012-01-31
1   2012-02-29
1   2012-03-31
2   2012-10-31
2   2012-11-30
2   2012-12-31

1 个答案:

答案 0 :(得分:2)

这个答案做了一些假设 - 没有比开始日期更大的结束日期,但你应该看看它是如何工作的。它创建一个递归联合CTE并使用它来计算结束日期

CREATE TABLE #Dates
(
    ID INT IDENTITY PRIMARY KEY,
    START_DATE DATETIME2(0) NOT NULL,
    END_DATE DATETIME2(0) NOT NULL
)

INSERT INTO #Dates VALUES ('2012-01-01', '2012-03-31'), ('2012-10-01','2012-12-31')

WITH MONTHS ([ID],[Month],[Date], [End])
AS
(
    SELECT ID, DATEPART(m,START_DATE) AS [Month], START_DATE AS [Date], DATEADD(s,-1,DATEADD(m,DATEDIFF(m,0,START_DATE)+1,0)) as [End]
    FROM #Dates
    UNION ALL
    SELECT D.ID, DATEPART(m,DATEADD(m,1,[Date])),DATEADD(m,1,[Date]), DATEADD(s,-1,DATEADD(m,DATEDIFF(m,0,DATEADD(m,1,[Date]))+1,0)) as [End]
    FROM #Dates D
    INNER JOIN  MONTHS M
    ON D.ID = M.ID
    WHERE DATEADD(m,1,[Date]) < [END_DATE]
)



SELECT * 
FROM MONTHS ORDER BY ID, Date

DROP TABLE #Dates