两列表转动

时间:2014-06-18 10:50:23

标签: sql sql-server-2008 pivot

我是sql pivot的新手并试图将两个列表转换为pivot

DECLARE @From date='1/1/2010',
        @To date ='1/1/2015'


Declare @TempDate datetime
Declare @xDate datetime
Set @xDate = @From 


Create Table #Dates(SYear int,StartDate datetime)

While (@xDate <= @To)
    Begin
        Set @TempDate = Convert(Datetime,Str(Month(@xDate)) + '/1/' + STR(Year(@xDate)))
        Insert Into #Dates values (Year(@TempDate),@TempDate)
        set @xDate =  DATEADD(YEAR, 1, @xDate)
    End     

---Getting these error message in pivot

列名&#34; StartDate&#34;在PIVOT运算符中指定的与PIVOT参数中的现有列名冲突。

列名&#34; SYear&#34;在PIVOT运算符中指定的与PIVOT参数中的现有列名冲突。

    Select SYear MyYear,StartDate FromDate
   From (
      Select SYear,StartDate
      From #Dates
     ) D
    Pivot(
        Max(SYear)
        For StartDate in (FromDate)
    )piv;

我正在尝试生成类似下面的内容

enter image description here

2 个答案:

答案 0 :(得分:0)

试试这个

Select SYear,StartDate
From #Dates
Pivot (
 Max(SYear)
 For #Dates in (StartDate,SYear)
 ) as pivottable;

答案 1 :(得分:-1)

您不需要使用pivot,您可以使用dynamic SQLcursor查看以下示例:

DECLARE @From date='1/1/2010',
        @To date ='1/1/2015'


Declare @TempDate datetime
Declare @xDate datetime
Set @xDate = @From 


Create Table #Dates(SYear int,StartDate datetime)

While (@xDate <= @To)
    Begin
        Set @TempDate = Convert(Datetime,Str(Month(@xDate)) + '/1/' + STR(Year(@xDate)))
        Insert Into #Dates values (Year(@TempDate),@TempDate)
        set @xDate =  DATEADD(YEAR, 1, @xDate)
    End    


---dynamic sql and cursor

DECLARE @increment int
SET @increment = 0;
DECLARE @sqlCommand nvarchar(1000)
DECLARE @datestring nvarchar(1000)
DECLARE @StartDate AS datetime;
DECLARE KURSOR_DY CURSOR FOR
        SELECT StartDate FROM #Dates GROUP BY StartDate;        
OPEN KURSOR_DY; 
FETCH NEXT FROM KURSOR_DY INTO @StartDate;  
WHILE @@FETCH_STATUS = 0
BEGIN   
    IF (@increment) = 0 
    BEGIN
        SET @datestring = '''' + '''' + ' as ['+convert(nvarchar(max), @StartDate, 103)+']'
    END
    IF (@increment) > 1
    BEGIN
        PRINT @datestring
        SET @datestring = @datestring + ', ''' + '''' + ' as ['+convert(nvarchar(max), @StartDate, 103)+']';
    END 
    FETCH NEXT FROM KURSOR_DY INTO @StartDate;  
    SET @increment = @increment + 1
END
CLOSE KURSOR_DY;    
DEALLOCATE KURSOR_DY;
SET @sqlCommand = 'SELECT SYear as [ ], '+ @datestring +
        ' FROM (select SYear, StartDate from #Dates) as A GROUP BY SYear';
EXEC(@sqlCommand)

drop table #Dates

结果:

enter image description here