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:

StudentID, Subject, and Score are as follows:

– Student 1 achieved 80 in Math and 75 in English.
– Student 2 scored 90 in Math and 85 in English.

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:

Student ID
Math Grade
English Grade

1
80
75

2
90
85

This achieves the function of converting rows to columns.

bannerAds