有这样一个表id   colname   value
-----------
1       A        A1
1       B        B1
1       C        C1
2       A        A2
2       B        B2    
2       C        C2
3       A        A3
3       B        B3
3       C        C3想把它变成如下的结构 A        B        C
------------
 A1       B1       C1
 A2       B2       C2
 A3       B3       C3
如何能办到?

解决方案 »

  1.   

    create table test
    (
    id int,
    colname varchar(10),
    value varchar(10)
    )
    insert test
    select 1,       'A',        'A1' union all
    select 1,       'B',        'B1' union all
    select 1,       'C',        'C1' union all
    select 2,       'A',        'A2' union all
    select 2,       'B',        'B2' union all    
    select 2,       'C',        'C2' union all
    select 3,       'A',        'A3' union all
    select 3,       'B',       'B3' union all
    select 3,       'C',        'C3'
    select * from testselect max(A) as A,max(B) as B,max(c) as C from 
    (select id,(case colname when 'A' then value
               end) A,
            (case colname when 'B' then value
                end) B,
            (case colname when 'C' then value
               end) C
    from test)tt group by id
      

  2.   

    --COLNAME 不确定
    --动态
    DECLARE  @SQL varchar(1000)
    SET @SQL=''
    SELECT  @SQL=@SQL +',' + 'MAX(case colname when  '''+colname+''' then value1 end) AS '''+COLNAME+'''' from tt group by colname
    SET @SQL=STUFF(@SQL,1,1,'')
    SET @SQL='SELECT '+@SQL +' FROM TT GROUP BY ID'
    EXEC(@SQL)
      

  3.   

    如果想永久保存表结构,则如下:select max(case colname when 'A' then value
               end) A,
            max(case colname when 'B' then value
                end) B,
            max(case colname when 'C' then value
               end) C
    into new_table
    from test group by id小虾米好像多套了一层查询呀.