create table #t([Year] int,[Month] int,DataValue int);
insert into #t select 2005,1,10
union all select 2005,2,20
union all select 2005,3,30
union all select 2005,4,40
union all select 2005,5,50
union all select 2005,6,60
union all select 2005,7,70
union all select 2005,12,120
union all select 2006,1,20
union all select 2006,2,40;
select * from #t;declare @sql varchar(8000);
set @sql='select year'
select @sql=rtrim(@sql)+',min(case month when '+rtrim(cast(month as char))+' then datavalue end) as ['+rtrim(cast(month as char))+'月]' from (select distinct month from #t) t;
set @sql=rtrim(@sql)+' from #t group by year';
print(@sql);
exec(@sql);
drop table #t;
怎么样把转成列的数据放到临时表中,怎么加都有错误的!!!晕

解决方案 »

  1.   

    没有错啊!/*
    2005 10 20 30 40 50 60 70 120
    2006 20 40 NULL NULL NULL NULL NULL NULL*/
      

  2.   

    create table #t([Year] int,[Month] int,DataValue int);
    insert into #t select 2005,1,10
    union all select 2005,2,20
    union all select 2005,3,30
    union all select 2005,4,40
    union all select 2005,5,50
    union all select 2005,6,60
    union all select 2005,7,70
    union all select 2005,12,120
    union all select 2006,1,20
    union all select 2006,2,40;
    select * from #t;declare @sql varchar(8000);
    set @sql='select year '
    select @sql=rtrim(@sql)+',min(case month when '+rtrim(cast(month as char))+' then datavalue end) as ['+rtrim(cast(month as char))+'月]' from (select distinct month from #t) t;
    set @sql=rtrim(@sql)+' into ##tt from #t group by year';exec(@sql)select * from ##ttyear        1月          2月          3月          4月          5月          6月          7月          12月         
    ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- 
    2005        10          20          30          40          50          60          70          120
    2006        20          40          NULL        NULL        NULL        NULL        NULL        NULL(2 row(s) affected)