SQL根据开始日期和结束日期创建日期值列表

时间:2018-04-04 14:56:16

标签: sql db2

我有一个观察数据集:

id        Starting date        Ending date    
23         18/8/2013             26/4/2014

我如何创建日期列表?即。

id       Date
23       Aug 2013
23       Sep 2013
23       Oct 2013
23       Nov 2013
23       Dec 2013
23       Jan 2014
23       Feb 2014
23       Mar 2014
23       Apr 2014

1 个答案:

答案 0 :(得分:1)

创建一个SQL表值函数,如下所示,这将生成日期。

CREATE FUNCTION fn_GenerateDates
(
    @StartDate DATETIME, 
    @EndDate DATETIME
)

RETURNS @Output TABLE 
(
      Value NVARCHAR(4000)
)

AS

BEGIN

    INSERT INTO @Output
    SELECT TOP (DATEDIFF(MONTH, @StartDate, @EndDate)+1) --get only the dates where dates are between the source startdate and enddate
            DATENAME(MONTH, DATEADD(MONTH, number, @StartDate)) + ' ' + CONVERT(VARCHAR(10), YEAR(DATEADD(MONTH, number, @StartDate))) AS Months
        FROM [master].dbo.spt_values 
        WHERE [type] = N'P' 
        ORDER BY number

    RETURN
END

然后你的SELECT语句

SELECT tn.id,
    dates.Value 
FROM TableName tn
CROSS APPLY dbo.fn_GenerateDates(tn.StartDate, tn.EndDate) AS dates
ORDER BY tn.id