Gurru
Gurru

Reputation: 2103

SQL how to create multiple row from a single row

Hi I am new to SQL server 2008

I want to expand a single row to multiple rows based on another colomn,

e.g

date          value
7-2011         5

Results:

2011-07-01     
2011-08-01
2011-09-01
2011-10-01
2012-11-01

the date shoild be first day of current and next month repeated 5 times

Upvotes: 3

Views: 11017

Answers (2)

Diego
Diego

Reputation: 36146

create  function addMonths(@date date, @limit int)
returns @date_table TABLE(
myDate date
)
AS
begin
  declare @cont int
  set @cont = 1
  while (@cont <= @limit) begin
    insert into @date_table values(DATEADD(MONTH,@cont,@date))
    set @cont=@cont+1
  end

  return 
end

usage:

select * from addMonths(GETDATE(),5)

EDIT:

create table mydates(
myDate date,
inc_months int)


insert into mydates values ('01/01/2005',3)
insert into mydates values ('01/01/2006',5)


select AM.mydate 
from mydates MD cross apply addMonths(MD.mydate,MD.inc_months) AM

result:

2005-02-01
2005-03-01
2005-04-01
2006-02-01
2006-03-01
2006-04-01
2006-05-01
2006-06-01

Upvotes: 2

KM.
KM.

Reputation: 103587

try:

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

output:

-----------------------
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)

it works with multiple rows in the table, see here:

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

OUTPUT:

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)

Also, I don't have SQL Server 2008 available, so I used datetime, if you have 2008, you can use DATE datatype and you don't have to floor the datetime, so use this line:

dateadd(month,number,y.YourDate)

Upvotes: 7

Related Questions