参考一下这个:
-----------------------------------------------------------------------------------------------------------------------------------
--测试数据
create table 基础表(姓名 nvarchar(10),课程名 nvarchar(20),成绩 decimal(10,1))
insert 基础表 select '王家喜','计算机基础',69.0
union  all   select '王家喜','邓小平理论',74.0
union  all   select '王家喜','英语(上)',86.0
union  all   select '王家喜','普通逻辑学',91.0
union  all   select '施春林','立法学教程',60.0
union  all   select '施春林','经管原理'  ,73.0
union  all   select '施春林','英语(上)',73.0
union  all   select '施春林','普通逻辑学',90.0
go--查询
declare @s varchar(8000),@i varchar(10)
select top 1 @s='',@i=count(*)
from 基础表 group by 姓名 order by count(*) desc
while @i>0
select @s=',[课程'+@i+']=max(case when id='+@i
+' then 课程名 else '''' end),[成绩'+@i
+']=max(case when id='+@i
+' then 成绩 end)'+@s
,@i=@i-1
exec('
select 姓名,课程名,成绩,id=0 into #t from 基础表 order by 姓名
declare @i int,@姓名 varchar(10)
update #t set @i=case when @姓名=姓名 then @i+1 else 1 end,id=@i,@姓名=姓名
select 姓名'+@s+' from #t group by 姓名')
go--删除测试
drop table 基础表/*--测试结果姓名    课程1        成绩1   课程2     成绩2   课程3     成绩3   课程4      成绩4  
-------- ----------- ------- --------- ------ --------- ------- ---------- -------
施春林   立法学教程  60.0    经管原理   73.0   英语(上) 73.0    普通逻辑学  90.0
王家喜   计算机基础  69.0    邓小平理论 74.0   英语(上) 86.0    普通逻辑学  91.0
--*/

解决方案 »

  1.   

    declare @s varchar(8000)
    set @s=''
    select @s=@s+',[h'+t.hh+'value]=max(case when right([date],2)='''+t.hh+''' then value end)' from (select hh=right([date],2),value from t1) t group by t.hh
    exec('select day=left([date],10),id,name'+@s+' from t1 group by left([date],10),id,name')
      

  2.   

    create table T1([date] varchar(13),[ID] int,[name] varchar(3),value varchar(3))
    insert t1
    select '2005-01-11 01',                 1,                'n11','v11' union all
    select '2005-01-11 01',                 1,                'n12','v12' union all    
    select '2005-01-11 02',                 1,                'n11','v13' union all
    select '2005-01-11 01',                 2,                'n21','n21'declare @s varchar(8000)
    set @s=''
    select @s=@s+',[h'+t.hh+'value]=max(case when right([date],2)='''+t.hh+''' then value end)' from (select hh=right([date],2),value from t1) t group by t.hh
    exec('select day=left([date],10),id,name'+@s+' from t1 group by left([date],10),id,name')--结果
    /*
    day           id          name h01value h02value 
    ------------- ----------- ---- -------- -------- 
    2005-01-11    1           n11  v11      v13
    2005-01-11    1           n12  v12      NULL
    2005-01-11    2           n21  n21      NULL
    */