select name,sum(case km when '语文' then cj end) as 语文,sum(case km when '数学' then cj end) as 数学,sum(case km when '英语' then cj end) as 英语 
into test_temp
from test 
group by namegoselect * from test_temp

解决方案 »

  1.   

    declare @sql varchar(8000)
    set @sql = 'select name'
    select @sql =@sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
      from (select distinct km from test) as a
    select @sql = @sql+' into #temp from test group by name ; select * from #temp'
    exec(@sql)
      

  2.   

    Create table test (name char(10),km char(10),cj int)
    go
    insert test values('张三','语文',80)
    insert test values('张三','数学',86)
    insert test values('张三','英语',75)
    insert test values('李四','语文',78)
    insert test values('李四','数学',85)
    insert test values('李四','英语',78)declare @sql varchar(8000)
    set @sql = 'select name'
    select @sql = @sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
    from (select distinct km from test) as a
    select @sql = @sql+' from test group by name'
    exec(@sql)drop table test
      

  3.   

    --处理
    declare @sql varchar(8000)
    set @sql = 'select name'
    select @sql =@sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
     from (select distinct km from test) as a
    select @sql = @sql+' into ##t from test group by name'
    exec(@sql)--显示处理生成的临时表
    select * from ##t--处理完成后删除临时表
    drop table ##t
      

  4.   

    --测试--测试数据
    Create table test (name char(10),km char(10),cj int)
    go
    insert test values('张三','语文',80)
    insert test values('张三','数学',86)
    insert test values('张三','英语',75)
    insert test values('李四','语文',78)
    insert test values('李四','数学',85)
    insert test values('李四','英语',78)
    go--处理
    declare @sql varchar(8000)
    set @sql = 'select name'
    select @sql =@sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
     from (select distinct km from test) as a
    select @sql = @sql+' into ##t from test group by name'
    exec(@sql)--显示处理生成的临时表
    select * from ##t--处理完成后删除临时表
    drop table ##t
    go--删除测试环境
    drop table test/*--测试结果
    name       数学          英语          语文          
    ---------- ----------- ----------- ----------- 
    李四         85          78          78
    张三         86          75          80(所影响的行数为 2 行)
    --*/
      

  5.   


    declare @sql varchar(8000)
    set @sql = 'select name'
    select @sql = @sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
     from (select distinct km from test) as a
    select @sql = @sql+' into #你的表 from test group by name  select * from #你的表'
    exec(@sql)
      

  6.   

    你可用普通表或全局臨時表,如果要用臨時表,就必須將 <#你的表>的生成與查詢放在一起執行,如:
    declare @sql varchar(8000)
    set @sql = 'select name'
    select @sql = @sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
     from (select distinct km from test) as a
    select @sql = @sql+' into #你的表 from test group by name  '
    exec(@sql)select * from #你的表  --會報錯找不到