declare @s varchar(8000)
set @s='select tu_date=str_date'
select @s=@s+',['+str_name+']=sum(case when str_num '''+str_name+''' then str_num else 0 end)' from tb group by str_name
set @s=@s+' from tb group by str_date order by str_date'
exec(@s)
set @s='select tu_date=str_date'
select @s=@s+',['+str_name+']=sum(case when str_num '''+str_name+''' then str_num else 0 end)' from tb group by str_name
set @s=@s+' from tb group by str_date order by str_date'
exec(@s)
create table table1(str_date int,str_num int,str_name varchar(10))
insert into table1
select 1, 34 ,'A' union all
select 1, 34 ,'A' union all
select 1, 25 ,'B' union all
select 2, 21 ,'B' union all
select 2, 34 ,'A' union all
select 2, 45 ,'C' union all
select 2, 23 ,'C'
--处理语句
declare @sql varchar(8000)
select @sql=''
select @sql=@sql+',sum(case str_name when '''+str_name+''' then str_num else 0 end) as '+str_name
from table1
group by str_name
exec('select str_date'+@sql+' from table1 group by str_date')
--删除测试表
drop table table1/*结果
1 68 25 0
2 34 21 68*/