create table #temp (id int , months int , total int)<br>insert #temp(id,months,total)<br>select 1001 , 1 , 80<br>insert #temp(id,months,total)<br>select 1002 , 1, 81<br>insert #temp(id,months,total)<br>select 1001 , 2 , 82<br>insert #temp(id,months,total)<br>select 1003 , 1 , 88<br>insert #temp(id,months,total)<br>select 1002 , 2 , 83<br>insert #temp(id,months,total)<br>select 1004 , 3 , 85<br><br>select * from #temp<br><br><br>DECLARE @SQL VARCHAR(8000) <br> set @sql = 'select id' <br> select @sql = @sql + ',sum(case months when '''+convert(varchar(20),months)+''' then total end) ['+convert(varchar(20),months)+']' <br> from (select distinct months from #temp) as a <br> select @sql = @sql+' from #temp group by id' <br>exec(@sql) <br><br><br>drop table #temp