create table tb(fid varchar(10),字段1 varchar(10),字段2 int)
insert into tb select  '1','aa',16                     
union all select '2','bb',17         
union all select '3','cc',18                   
union all select '4','dd',19                      
declare @sql varchar(8000)
set @sql='select fid'
select @sql=@sql+',['+字段1+']=sum(case 字段1 when '''+字段1+''' then 字段2 else null end)' from tb group by 字段1
exec(@sql+' from tb group by fid')drop table tb

解决方案 »

  1.   

    create table tb(fid varchar(10),字段1 varchar(10),字段2 int)
    insert into tb select  '1','aa',16                     
    union all select '2','bb',17         
    union all select '3','cc',18                   
    union all select '4','dd',19
    union all select '1','aa',20                    
    declare @sql varchar(8000)
    set @sql='select isnull(fid,''合计'')'
    select @sql=@sql+',['+字段1+']=sum(case 字段1 when '''+字段1+''' then 字段2 else null end)' from tb group by 字段1
    exec(@sql+' from tb group by fid with rollup')drop table tb
    --这样?