sql server中的 行转列
PIVOT syntax:
FOR pivot_column
IN ( <column_list> )
)
CREATE TABLE Score ( StuNo varchar(10), StuName varchar(50), CourseName varchar(50), Score int); GO INSERT INTO Score (StuNo, StuName, CourseName, Score) VALUES (‘1‘, ‘Tom‘, ‘Math‘, 80); INSERT INTO Score (StuNo, StuName, CourseName, Score) VALUES (‘1‘, ‘Tom‘, ‘English‘, 82); INSERT INTO Score (StuNo, StuName, CourseName, Score) VALUES (‘1‘, ‘Tom‘, ‘Geography‘, 84); INSERT INTO Score (StuNo, StuName, CourseName, Score) VALUES (‘2‘, ‘Jone‘, ‘Math‘, 79); INSERT INTO Score (StuNo, StuName, CourseName, Score) VALUES (‘2‘, ‘Jone‘, ‘English‘, 88); INSERT INTO Score (StuNo, StuName, CourseName, Score) VALUES (‘2‘, ‘Jone‘, ‘Geography‘, 86); GO SELECT * FROM Score;
1 Tom Math 80
1 Tom English 82
1 Tom Geography 84
2 Jone Math 79
2 Jone English 88
2 Jone Geography 86
--Change row to column:
SELECT StuNo, StuName, Math, English, Geography FROM Score PIVOT ( MAX(Score) FOR CourseName in (Math, English, Geography) ) AS ScoreList ORDER BY StuNo;
1 Tom 80 82 84
2 Jone 79 88 86
DROP TABLE Score; GO
CREATE TABLE ScoreList ( StuNo varchar(10), StuName varchar(50), Math int, English int, Geography int); GO INSERT INTO ScoreList (StuNo, StuName, Math, English, Geography) VALUES (‘1‘, ‘Tom‘, 80, 82, 84); INSERT INTO ScoreList (StuNo, StuName, Math, English, Geography) VALUES (‘2‘, ‘Jone‘, 79, 88, 86); GO SELECT * FROM ScoreList;
1 Tom 80 82 84
2 Jone 79 88 86
--Change column values to row: SELECT StuNo, StuName, CourseName, Score FROM ScoreList UNPIVOT ( Score FOR CourseName in (Math, English, Geography) ) AS ScorePvtTable ORDER BY StuNo;
1 Tom Math 80
1 Tom English 82
1 Tom Geography 84
2 Jone Math 79
2 Jone English 88
2 Jone Geography 86
DROP TABLE ScoreList; GO
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。