http://community.csdn.net/Expert/topic/3421/3421357.xml?temp=.8397333

解决方案 »

  1.   

    --交叉表查询
    select stu,数学=max(case course when '数学' then score else 0 end),
               语文=max(case course when '语文' then score else 0 end)
    from new
    group by stu
    /*
    结果
    stu         数学          语文          
    ----------- ----------- ----------- 
    1           89          90
    2           34          45(所影响的行数为 2 行)
    */
      

  2.   

    select  stu,course,score from ( (select stu,course,score from  我有一个表 where course =语文)t1 left join (select stu,course,score from 还是那个表 where course = 数学)t2 on 
    t1.stu =t2.stu)
      

  3.   


    举个例子:
    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)
    想得到:
    姓名   语文   数学   英语
    张三   80     86     75
    李四   78     85     78declare @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)
      

  4.   

    我想这个问题的解决应该这样:
    1:可以使用子查询,每个子查询中将所有的科目同人名连接起来。
    2:对子查询使用全外连接,避免由于某些科目没有成绩而丢失数据。
    3:如果科目不定的话,最好使用一个可以动态生成的sql语句。