create table T ( 姓名 nvarchar(20), 成果 int ) insert into T select '张三', 1 union all select '张三', 1 union all select '张三', 2 union all select '张三', 2 union all select '李四', 1 union all select '李四', 1 union all select '李四' , 2 declare @s nvarchar(200) set @s='' select @s=@s+',sum(case when 成果='''+cast(成果 as nvarchar(20))+''' then 1 else 0 end) as ['+cast(成果 as nvarchar(20))+']' from T group by 成果exec ('select 姓名'+@s+' from T group by 姓名')
(
姓名 nvarchar(20),
成果 int
)
insert into T
select
'张三', 1 union all
select '张三', 1 union all
select '张三', 2 union all
select '张三', 2 union all
select '李四', 1 union all
select '李四', 1 union all
select '李四' , 2
declare @s nvarchar(200)
set @s=''
select @s=@s+',sum(case when 成果='''+cast(成果 as nvarchar(20))+''' then 1 else 0 end) as ['+cast(成果 as nvarchar(20))+']'
from T
group by 成果exec ('select 姓名'+@s+' from T group by 姓名')