一、行轉列
1、測試數據准備
CREATE TABLE [StudentScores] ( [UserName] NVARCHAR(20), --學生姓名 [Subject] NVARCHAR(30), --科目 [Score] FLOAT, --成績 ) INSERT INTO [StudentScores] SELECT '張三', '語文', 80 INSERT INTO [StudentScores] SELECT '張三', '數學', 90 INSERT INTO [StudentScores] SELECT '張三', '英語', 70 INSERT INTO [StudentScores] SELECT '張三', '生物', 85 INSERT INTO [StudentScores] SELECT '李四', '語文', 80 INSERT INTO [StudentScores] SELECT '李四', '數學', 92 INSERT INTO [StudentScores] SELECT '李四', '英語', 76 INSERT INTO [StudentScores] SELECT '李四', '生物', 88 INSERT INTO [StudentScores] SELECT '碼農', '語文', 60 INSERT INTO [StudentScores] SELECT '碼農', '數學', 82 INSERT INTO [StudentScores] SELECT '碼農', '英語', 96 INSERT INTO [StudentScores] SELECT '碼農', '生物', 78
執行結果:

2、行轉列sql
SELECT * FROM [StudentScores] /*數據源*/ AS P PIVOT ( SUM(Score/*行轉列后 列的值*/) FOR p.Subject/*需要行轉列的列*/ IN ([語文],[數學],[英語],[生物]/*列的值*/) ) AS T
執行結果:

二、列轉行
1、測試數據准備
CREATE TABLE ProgrectDetail ( ProgrectName NVARCHAR(20), --工程名稱 OverseaSupply INT, --海外供應商供給數量 NativeSupply INT, --國內供應商供給數量 SouthSupply INT, --南方供應商供給數量 NorthSupply INT --北方供應商供給數量 ) INSERT INTO ProgrectDetail SELECT 'A', 100, 200, 50, 50 UNION ALL SELECT 'B', 200, 300, 150, 150 UNION ALL SELECT 'C', 159, 400, 20, 320 UNION ALL
執行結果:

2、列轉行的sql
SELECT P.ProgrectName,P.Supplier,P.SupplyNum FROM ( SELECT ProgrectName, OverseaSupply, NativeSupply, SouthSupply, NorthSupply FROM ProgrectDetail )T UNPIVOT ( SupplyNum FOR Supplier IN (OverseaSupply, NativeSupply, SouthSupply, NorthSupply ) ) P
執行結果:

