declare @sql varchar(8000) set @sql='select t3.BID,t5.UnitName,Sort,UnitTypeSort' select @sql=@sql+' , max(case t4.id when '''+ ID +''' then t3.Num else 0 end) ['+ Name +']' from (select distinct ID,Name from Per_Dictionary where type='47') as a set @sql=@sql+' from DS_HZ_ResourceType t3 inner join Per_Dictionary t4 on t3.RID=t4.id left join v_DS_DW_BaseIfo t5 on t3.BID=t5.ID group by t3.BID,t5.UnitName,Sort,UnitTypeSort' print @sql exec(@sql)