SQL如何从单行创建多行

Gur*_*rru 3 sql-server-2008

嗨,我是SQL Server 2008的新手

我想根据另一列将单行扩展为多行,

例如

date          value
7-2011         5
Run Code Online (Sandbox Code Playgroud)

结果:

2011-07-01     
2011-08-01
2011-09-01
2011-10-01
2012-11-01
Run Code Online (Sandbox Code Playgroud)

日期紧缩为当前第一天,下个月重复5次

KM.*_*KM. 5

尝试:

DECLARE @YourTable table (YourDate datetime, value int)

insert into @YourTable VALUES ('2011-7-12',5)

;WITH AllNumbers AS
(
    SELECT 0 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<4
)
SELECT 
    dateadd(month,number,DATEADD(month,DATEDIFF(month,0,YourDate),0))
    FROM @YourTable        y
    INNER JOIN AllNumbers  a ON 1=1
Run Code Online (Sandbox Code Playgroud)

输出:

-----------------------
2011-07-01 00:00:00.000
2011-08-01 00:00:00.000
2011-09-01 00:00:00.000
2011-10-01 00:00:00.000
2011-11-01 00:00:00.000

(5 row(s) affected)
Run Code Online (Sandbox Code Playgroud)

它适用于表中的多行,请参见此处:

DECLARE @YourTable table (YourDate datetime, ValueOf int)

insert into @YourTable VALUES ('2011-7-12',5)
insert into @YourTable VALUES ('2012-4-24',6)

;WITH AllNumbers AS
(
    SELECT 0 AS Number
    UNION ALL
    SELECT Number+1
        FROM AllNumbers
        WHERE Number<4
)
SELECT 
    y.ValueOf
        ,dateadd(month,number,DATEADD(month,DATEDIFF(month,0,y.YourDate),0))
    FROM @YourTable        y
    INNER JOIN AllNumbers  a ON 1=1
    ORDER BY 1,2
Run Code Online (Sandbox Code Playgroud)

输出:

ValueOf     
----------- -----------------------
5           2011-07-01 00:00:00.000
5           2011-08-01 00:00:00.000
5           2011-09-01 00:00:00.000
5           2011-10-01 00:00:00.000
5           2011-11-01 00:00:00.000
6           2012-04-01 00:00:00.000
6           2012-05-01 00:00:00.000
6           2012-06-01 00:00:00.000
6           2012-07-01 00:00:00.000
6           2012-08-01 00:00:00.000

(10 row(s) affected)
Run Code Online (Sandbox Code Playgroud)

另外,我没有可用的SQL Server 2008,所以我使用的是datetime,如果您使用的是2008,则可以使用DATE数据类型,而不必限制日期时间,因此请使用以下行:

dateadd(month,number,y.YourDate)
Run Code Online (Sandbox Code Playgroud)