比如有表A,结构如下:
 姓名   课程  成绩
  A     语文  30
  A    数学   40
  B    数论   50
  B    英语   20
  B    中文   44
  C    语文   35变成如下结果:
姓名   课程  成绩   课程  成绩 课程  成绩 
A      语文  30    数学  40  null  null
B      数论   40   英语  20   中文   44
C      语文   35   null  null null  null

解决方案 »

  1.   

    select COALESCE(a.name,b.name,c.name,d.name),a.class,a.score
    ,b.class,b.score,c.class,c.score,d.class,d.score
    from tb a full join tb b on a.name=b.name full join tb c on a.name=c.name
    full join tb d on a.name=d.name
    where a.class='语文' and b.class='数学' and c.class='英语' and d.class='中文'貌似不太符合呵呵
      

  2.   

    create table tb(姓名 varchar(10),课程 varchar(10), 成绩 int)
    insert into tb values('A','语文', 30)
    insert into tb values('A','数学', 40)
    insert into tb values('B','数论', 50)
    insert into tb values('B','英语', 20)
    insert into tb values('B','中文', 44)
    insert into tb values('C','语文', 35)
    godeclare @sql varchar(8000)
    set @sql = 'select 姓名 '
    select @sql = @sql + ' , max(case px when ''' + cast(px as varchar) + ''' then 课程 else null end) ''课程'''
                       + ' , max(case px when ''' + cast(px as varchar) + ''' then 成绩 else null end) ''成绩'''
    from (select distinct px from (select t.* , px = (select count(1) from tb where 姓名 = t.姓名 and 课程 < t.课程) +  1 from tb t) m) as a
    set @sql = @sql + ' from (select t.* , px = (select count(1) from tb where 姓名 = t.姓名 and 课程 < t.课程) +  1 from tb t)m group by 姓名'
    exec(@sql) drop table tb/*
    姓名         课程         成绩          课程         成绩          课程         成绩          
    ---------- ---------- ----------- ---------- ----------- ---------- ----------- 
    A          数学         40          语文         30          NULL       NULL
    B          数论         50          英语         20          中文         44
    C          语文         35          NULL       NULL        NULL       NULL
    */