请教哈各位大侠,在一张表中如下面:ID  A    B    C
1  78    86   58
2   65   56   89
3   78   98   56
现在我要得到如下表:
ID    1    2     3
A     78   65    78
B     86   56    98
C     58   89    56
请问我要用SQL语句如何实现??

解决方案 »

  1.   

    create table t1(id int,a int,b int,c int)
    insert into t1
    select 1,78,86,58
    union select 2,65,56,89
    union select 3,78,98,56
    union select 5,10,29,16
    union select 9,38,68,47
    go
    --select * from t1
    declare @sql varchar(4000)
    set @sql='create table t2(id varchar(20)'
    select @sql=@sql+',['+cast(id as varchar)+'] int' from t1
    set @sql=@sql+')'
    exec(@sql)
    declare @colname varchar(20),@rowstring varchar(1000),@sql2 nvarchar(4000)
    declare cur cursor for select name from syscolumns where id=object_id('t1') and colid>1
    open cur
    fetch next from cur into @colname
    while @@fetch_status=0
    begin
    set @sql='insert into t2 select '''+@colname+''''
    set @sql2='select @sql=@sql+'',''+cast('+@colname+' as varchar) from t1 '
    exec sp_executesql @sql2,N'@sql varchar(4000) out',@sql out
    exec(@sql)
    fetch next from cur into @colname
    end
    deallocate cur
    select * from t2
    go
    drop table t1,t2
      

  2.   

    看看一楼的代码,我发现在SQL里这么写简直是折磨自己。
      

  3.   

    我宁愿有程序来完成 也不会写这么复杂的sql