動態SQL對各列進行求和運算

如下表:

  id  F1    F2    F3   F4   F5   F6......
   1  a     b     12   25   10   20
   2  a     b     20    5    10   21
   3  c     d     12    123  1   21

我想達到如下效果
將F1,F2相同記錄進行合併後只保留一條(列出所有字段),並對F3進行SUM求和

請問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')

drop table tb

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章