本帖最后由 cejay 于 2010-09-03 08:07:28 编辑

解决方案 »

  1.   


    我的表结构:   
      ID(主键)     studentNo   courseNo   score   
      1                     01                 2001         99   
      2                     01                 2002         98   
      3                     01                 2003         97   
      4                     02                 2001         95   
      5                     02                 2002         94   
      6                     02                 2003         93   
        
      查询结果   
      studentNo     2001           2002           2003   
      01                       99               98               97   
      02                       95               94               93 方法1:
    declare   @s   varchar(8000)   
      set   @s=@s+',['+cast(courseNo   as   varchar)+']=sum(case   courseNo   when   '''+cast(courseNo   as   varchar)+'''   then   score   end)'   
      from   表   
      group   by   courseNo   
      exec('select   studentNo'+@s+'   from   表   group   by   studentNo')
    方法2:
    select   studentNo   
              ,[2001]=sum(case   courseNo   when   '2001'   then   score   end)   
              ,[2002]=sum(case   courseNo   when   '2002'   then   score   end)   
              ,[2003]=sum(case   courseNo   when   '2003'   then   score   end)   
      from   表   
      group   by   studentNo   
      

  2.   

    http://topic.csdn.net/u/20091018/15/7c6729b6-79d1-492e-862d-af9c4921f172.html?91738
      

  3.   

    sql 列转行,这个网上很多很多了。