sql的行轉列(PIVOT)與列轉行(UNPIVOT)
阿新 • • 發佈:2018-02-23
列轉行 gif 而且 碼農 實現 score username info rect
在做數據統計的時候,行轉列,列轉行是經常碰到的問題。case when方式太麻煩了,而且可擴展性不強,可以使用 PIVOT,UNPIVOT比較快速實現行轉列,列轉行,而且可擴展性強
一、行轉列
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
執行結果:
sql的行轉列(PIVOT)與列轉行(UNPIVOT)