SQL Pivot: Convert Rows to Columns
In SQL Server, you can use the PIVOT operator to transform rows into columns. Below is an example:
Suppose there is a table named StudentScore, which contains the following data:
To pivot the rows of data above, you can utilize the following SQL query:
SELECT StudentID, [Math], [English]
FROM
(SELECT StudentID, Subject, Score
FROM StudentScore) AS SourceTable
PIVOT
(
MAX(Score)
FOR Subject IN ([Math], [English])
) AS PivotTable;
After performing the above query, you will obtain the following results:
This achieves the function of converting rows to columns.