select sum(a) as a,sum(b) as b ,sum(c) as c ,sum(d) as d,sum(e) as e
from (
select 'aa' as aa,case f2 when 'a' then f1 else 0 end as a,
case f2 when 'b' then f1 else 0 end as b,
case f2 when 'c' then f1 else 0 end as c,
case f2 when 'd' then f1 else 0 end as d,
case f2 when 'e' then f1 else 0 end as e
from table1) abc
group by abc.aa
/*測試數據*/
create table t (f1 int,f2 varchar(2))
insert into t
select 1,'a'
union
select 2,'b'
union
select 3,'c'
union
select 4,'d'
union
select 5,'e'
/*語句*/
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',max(case when f2='''+f2+''' then f1 end) as '+f2 from T group by f2
set @sql='select '+stuff(@sql,1,1,'')+' from T'
exec(@sql)
/*The result:*/
a b c d e
----------- ----------- ----------- ----------- -----------
1 2 3 4 5