有一个表table1
id name  科目    成绩
1  a    chinese   56
2  b    chinese   45
3  a    english   65
4  b     english  87我想得到这样的表name  chinese   english
a      56        45
b      45         87
怎么写。

解决方案 »

  1.   

    如果科目固定只有chinese和english的話這樣就可以了select name, chinese = max(case 科目 when 'chinese' then 成績 else null end),
    english = max(case 科目 when 'engligh' then 成績 else null end)
    from table1
    group by name
      

  2.   

    如果科目不固定的話必須用動態SQLdeclare @s varchar(8000)
    select @s = isnull(@s, '') + ', max(case 科目 when ''' + 科目 + ''' then 成績 else null) as [' + 科目 + ']'
    from table1
    set @s = stuff(@s, 1, 1, '')
    set @s = 'select name,' + @s + ' from table1 group by name'exec(@s)
      

  3.   

    echiynn(寶琲) 
    你的第二个方法好象过不去
      

  4.   

    declare @s varchar(8000)
    select @s = isnull(@s, '') + ', max(case 科目 when ''' + 科目 + ''' then 成績 else null end) as [' + 科目 + ']'
    from table1
    set @s = stuff(@s, 1, 1, '')
    set @s = 'select name,' + @s + ' from table1 group by name'exec(@s)------------
    剛才case語句掉了end
      

  5.   

    还不对,
    name              chinese  mathes   maths    chinese   English  English  chinese
    hua        85 NULL NULL 85 NULL NULL 85
    tai        52 78 78 52 95 95 52       
    wei        84 62 62 84 76 76 84有重复的
      

  6.   

    暈,又掉了group bydeclare @s varchar(8000)
    select @s = isnull(@s, '') + ', max(case 科目 when ''' + 科目 + ''' then 成績 else null end) as [' + 科目 + ']'
    from table1
    group by 科目 --這裏加上
    set @s = stuff(@s, 1, 1, '')
    set @s = 'select name,' + @s + ' from table1 group by name'exec(@s)
      

  7.   

    echiynn(寶琲)
    那个max()是什么意思