2012-04-24 50 views
2

您好我是新來的SQL服務器2008SQL如何從單行

我想擴大單行基於另一個colomn多行創建多個行,

date   value 
7-2011   5 

結果:

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

日期shoild是當前和下一個月份的第一天重複5次

回答

4

嘗試:

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 

輸出:

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

它多行的工作表中,在這裏看到:

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) 

另外,我沒有SQL Server 2008中可用,所以我用日期時間,如果你有2008,你可以使用DATE數據類型,你不必地板的日期時間,所以用這條線:

dateadd(month,number,y.YourDate) 
+0

感謝,但是我有不同的月份和價值觀,我的表想的價值觀不是一個單一的價值分裂 – Gurru 2012-04-24 13:37:46

+0

您好感謝它的工作原理,但如何動態地選擇日期,並從價值表而不是手動設置它們? – Gurru 2012-04-24 13:51:01

+0

我不確定你在問什麼?你總是可以添加一個'WHERE ValueOf = 6'或類似的東西。 – 2012-04-24 14:44:06

2
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 @[email protected]+1 
    end 

    return 
end 

用法:

select * from addMonths(GETDATE(),5) 

編輯:

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 

重SULT:

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

,但在函數 – 2012-04-24 13:31:30

+0

內使用GETDATE()好點。謝謝 – Diego 2012-04-24 13:40:00

+0

謝謝你們,但重點是我不想通過@日期和價值,我必須從另一張桌子上選擇他們,並在我的新表中做擴展我有例如1000行和值是否意味着我將不得不傳遞參數1000?而不是從現有的表中選擇它們? – Gurru 2012-04-24 14:04:04