id name subject score remark
1 l math 86
2 l eng 68
3 l phy 88
4 z chn 99
5 z math 92
6 z com 98
7 z pe 95
8 p chn 93
9 p art 92
--4:动态PIVOT行转列
DECLARE @sql_str VARCHAR(8000)
DECLARE @sql_col VARCHAR(8000)
SELECT @sql_col = ISNULL(@sql_col + ',','') + QUOTENAME([Subject]) FROM [student2] GROUP BY [Subject]
SET @sql_str = '
SELECT * FROM (
SELECT [Name],[Subject],[score] FROM [student2]) p PIVOT
(SUM([Score]) FOR [Subject] IN ( '+ @sql_col +') ) AS pvt
ORDER BY pvt.[Name]'
PRINT (@sql_str)
EXEC (@sql_str)