declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',sum(case name when '''+name+''' then value else 0 end) ['+name+']'
from t group by name
exec('select id'+@sql+' from t group by id order by id')

解决方案 »

  1.   

    select id
      ,col1=sum(case name when 'col1' then value else 0 end)
      ,col2=sum(case name when 'col2' then value else 0 end)
      ,col3=sum(case name when 'col3' then value else 0 end)
    from 表a
    group by id
      

  2.   

    to  zjcxc(邹建) 列的数量和名称是不固定的!!
      

  3.   

    在oracle中好处理.sql server中不会,
      

  4.   

    只是用sql,在什么dbms上有区别吗?
      

  5.   

    问题还没有解决,老大们帮我看看,解决了 我一起给分!地址如下:
    http://community.csdn.net/Expert/topic/3345/3345955.xml?temp=.1271326
      

  6.   

    to zheninchangjiang(我爱燕子)问题还没有解决啊!
      

  7.   

    --示例--示例数据
    create table testtt(id int,name varchar(10),value1 varchar(10))
    insert testtt select 1,'11','56'        
    union  all    select 1,'22','fgh'
    union  all    select 2,'11','7'
    union  all    select 2,'22','m'
    go--查询
    declare @sql varchar(8000)
    set @sql=''select @sql=@sql + ',['+rtrim(name)+']=max(case name when '''+rtrim(name)+''' then rtrim(value1) else '''' end)'
    from testtt
    group by name
    exec('select id'+@sql+'
    from  testtt group by id order by id')
    go--删除测试
    drop table testtt/*--测试结果id          11         22         
    ----------- ---------- ---------- 
    1           56         fgh
    2           7          m
    --*/
      

  8.   

    如果varchar(8000)的长度不够怎么处理?
    declare @sql varchar(8000)
    set @sql=''select @sql=@sql + ',['+rtrim(name)+']=max(case name when '''+rtrim(name)+''' then rtrim(value1) else '''' end)'
    from testtt
    group by name
    exec('select id'+@sql+'
    from  testtt group by id order by id')