PIVOT Syntax:
SELECT ..... From
pivoted_table
pivoted_table:: =
Table_sourcePIVOT <
Pivot_clause>
Table_alias
table_source:: =Table,view, Sub-query,xml ..., that is, the SQL statement from the keyword can be followed by everything, the definition is too complex, here is not written
pivot_clause:: =(
aggregate_function
(
Value_column
)
For
pivot_column
Inch
(<column_list>
)
)
UNPIVOT Syntax:SELECT ..... From
unpivoted_table
unpivoted_table:: =
Table_sourceUNPIVOT <
Unpivot_clause>
Table_alias
table_source:: =Table, view, Sub-query, XML ..., which is everything that can be followed by the SQL statement from the keyword, is too complex to be written here.
Unpivot
_clause:: =(
Value_columnFor
pivot_columnIn (<column_list>))
PIVOT Example:
CREATE TABLEScore (Stunovarchar(Ten), Stunamevarchar( -), Coursenamevarchar( -), scoreint); GO INSERT intoScore (Stuno, Stuname, Coursename, score)VALUES('1','Tom','Math', the); INSERT intoScore (Stuno, Stuname, Coursename, score)VALUES('1','Tom','中文版', the); INSERT intoScore (Stuno, Stuname, Coursename, score)VALUES('1','Tom','Geography', -); INSERT intoScore (Stuno, Stuname, Coursename, score)VALUES('2','Jone','Math', -); INSERT intoScore (Stuno, Stuname, Coursename, score)VALUES('2','Jone','中文版', the); INSERT intoScore (Stuno, Stuname, Coursename, score)VALUES('2','Jone','Geography', the); GO SELECT * fromScore;
Stuno Stuname Coursename Score
1 Tom Math 80
1 Tom 中文版 82
1 Tom Geography 84
2 Jone Math 79
2 Jone 中文版 88
2 Jone Geography 86
--Changerow to column:
SELECT Stuno, Stuname, Math, 中文版, Geography from score MAX scorelist ORDER by Stuno;
Stuno stuname Math 中文版 Geography
1 Tom 80 82 84
2 Jone 79 88 86
DROP TABLE score; GO
UNPIVOT Example:
CREATE TABLEScorelist (Stunovarchar(Ten), Stunamevarchar( -), Mathint, 中文版int, Geographyint); GO INSERT intoScorelist (Stuno, Stuname, Math, 中文版, Geography)VALUES('1','Tom', the, the, -); INSERT intoScorelist (Stuno, Stuname, Math, 中文版, Geography)VALUES('2','Jone', -, the, the); GO SELECT * fromScorelist;
Stuno stuname Math 中文版 Geography
1 Tom 80 82 84
2 Jone 79 88 86
-- Change column values to row: SELECT Stuno, Stuname, Coursename, score from scorelist for inch as scorepvttable ORDER by
Stuno Stuname Coursename Score
1 Tom Math 80
1 Tom 中文版 82
1 Tom Geography 84
2 Jone Math 79
2 Jone 中文版 88
2 Jone Geography 86
DROP TABLE scorelist; GO
Row-to-column in SQL Server