表结构
A B C D
w f ff 100
2 df df 200
ff ff ff 300
查询出来的结果:
ff df
400 200
也就说把C列横着排列,并把C列中相同的列求D的和
解决:
create table #A (A varchar(11),B varchar(11),C varchar(11),D int)
insert into #A
select 'w','f','ff',100 union all
select '2','df','df',200 union all
select 'ff','ff','ff',300
-->2000动态
declare @cols varchar(8000)
select @cols=isnull(@cols+',','')+'['+C+']=sum(case C when '''+C+''' then D end)' from #A group by C
exec ('select '+@Cols+' from #A')
/*
df ff
----------- -----------
200 400
*/