-- Test Data
Declare @ tab table (ID varchar (3), Class varchar (10), sums INT)
Insert @ Tab
Select '001', 'computer ', '65' Union all
Select '002 ', 'computer', '75' Union all
Select '001', 'artbe', '77 'Union all
Select '003 ', 'sport', '54' Union all
Select '004 ', 'artbe', '65' Union all
Select '005 ', 'sport', '55' Union all
Select '001', 'sport', '56' Union all
Select '002 ', 'Sports', '88 'Union all
Select '002 ', 'artbe', '98' Union all
Select '003 ', 'computer', '82 'Union all
Select '003 ', 'artbe', '92' Union all
Select '004 ', 'computer', '85 'Union all
Select '004 ', 'sport', '25' Union all
Select '005 ', 'computer', '89 'Union all
Select '005 ', 'artbe', '99 ';
-- Select * From @ Tab
-- Below is the testCode
Select * into # temp1 from @ Tab
Declare @ STR varchar (8000)
Set @ STR = 'select ID as number ,'
Select @ STR = @ STR +'
Sum (case class when ''' + class + ''' then sums else 0 end) as ''' + class + 'score '+ ''','
From (select distinct class from # temp1) T
Set @ STR = left (@ STR, Len (@ Str)-1) + 'from # temp1 group by id'
Exec (@ Str)
Drop table # temp1
/* The following is the test result.
(15 rows are affected)
(15 rows are affected)
Number, computer score, art score, sports score
-------------------------------------
001 65 77 56
002 75 98 88
003 82 92 54
004 85 65 25
005 89 99 55 */