SELECT ID,
(case homework WHEN 'work1' THEN score else 0 end ) as work1,
(case homework WHEN 'work2' THEN score else 0 end ) as work2,
(case homework WHEN 'work3' THEN score else 0 end ) as work3,
(case homework WHEN 'work4' THEN score else 0 end ) as work4,
(case homework WHEN 'work5' THEN score else 0 end ) as work5
FROM TableXX
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(homework)
FROM (SELECT DISTINCT homework FROM tablename) AS TableTemp
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT id, ' + @ColumnName + '
FROM tablename
PIVOT(SUM(score)
FOR homework IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery