create table row_to_column
(
code int,
name varchar(10),
value int
)
insert into row_to_column
select 1,'name1',20
union
select 2,'name1',30
union
select 1,'name2',30
union
select 2,'name2',30
union
select 3,'name3',20
union
select 1,'name3',20
union
select 2,'name3',30select * from row_to_column
select distinct name from row_to_column--select code,sum(case when name='name1' then value else 0 end) as name1,
-- sum(case when name='name2' then value else 0 end) as name2,
-- sum(case when name='name3' then value else 0 end) as name3
-- from row_to_column
-- group by codedeclare @sql varchar(8000)
set @sql=''
SELECT @sql = @sql + N',' + quotename(name) + N'= SUM(CASE name WHEN ' + QUOTENAME(name, '''') + ' THEN value ELSE 0 END)'
FROM(
SELECT DISTINCT name FROM row_to_column
)A
--print @sql
set @sql =substring(@sql,2,len(@sql))
--print @sql
EXEC('
select code,'+ @sql + '
FROM row_to_column
GROUP BY code')