--try declare @sql varchar(max) set @sql='' select @sql=@sql+',max(case when month='''+month+''' then num else '''' end)['+month+']' from (select month from table)u order by [month] set @sql=stuff(@sql,1,1,'') set @sql='select id,'+@sql+' from tb_ot group by id' exec(@sql)
declare @sql varchar(max) set @sql='' select @sql=@sql+',max(case when month='''+month+''' then num else '''' end)['+month+']' from (select month from table)u order by [month] set @sql=stuff(@sql,1,1,'') set @sql='select id,'+@sql+' from tb_ot group by id' exec(@sql)
declare @sql varchar(max)
set @sql=''
select @sql=@sql+',max(case when month='''+month+''' then num else '''' end)['+month+']' from (select month from table)u
order by [month]
set @sql=stuff(@sql,1,1,'')
set @sql='select id,'+@sql+' from tb_ot group by id'
exec(@sql)
set @sql=''
select @sql=@sql+',max(case when month='''+month+''' then num else '''' end)['+month+']' from (select month from table)u
order by [month]
set @sql=stuff(@sql,1,1,'')
set @sql='select id,'+@sql+' from tb_ot group by id'
exec(@sql)