declare @sql varchar(4000) set @sql = 'select Name' select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']' from (select distinct Subject from CJ) as a select @sql = @sql+' from test group by name' exec(@sql)
select a.name,sum(a.ch) as [ch],sum(a.en) as [en],sum(a.ph) as [ph] from( select name,score as [ch],'' as [en],'' as [ph] from table where object='ch' union select name,'',score as [en],'' from table where object='en' union select name,'','',score as [ch] as [ph] from table where object='ph' ) a group by a.name
select name,sum(case object when ch then isnull(score,0) else o end) as ch,sum(case object when eh then isnull(score,0) else o end) as eh,sum(case object when ph then isnull(score,0) else o end) as ph from table group by name