create table tb(id int,F1 varchar(10),F2 varchar(10),F3 int,F4 int,F5 int,F6 int)
insert into tb select 1,'a','b',12,25,10,20
union all select 2,'a','b',20,5,10,21
union all select 3,'c','d',12,123,1,21
go
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+','+name from syscolumns where id=object_id('tb') and name not in('id','F1','F2','F3') order by colid --写不要汇总的列名
exec('select F1,F2,sum(F3) as F3'+@sql+' from tb group by F1,F2'+@sql)
--动态SQL
create table tb(id int,F1 varchar(10),F2 varchar(10),F3 int,F4 int,F5 int,F6 int)
insert into tb select 1,'a','b',12,25,10,20
union all select 2,'a','b',20,5,10,21
union all select 3,'c','d',12,123,1,21
go
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',sum('+name+') as '+name from syscolumns where id=object_id('tb') and name not in('id','F1','F2') order by colid --写不要汇总的列名
exec('select F1,F2'+@sql+' from tb group by F1,F2')
create table tb(id int,F1 varchar(10),F2 varchar(10),F3 int,F4 int,F5 int,F6 int)
insert into tb select 1,'a','b',12,25,10,20
union all select 2,'a','b',20,5,10,21
union all select 3,'c','d',12,123,1,21
go