Introduction
As we learn Pivot Table in the previous article.
UnPivot is another operation in SQL that perform almost reverse operation of Pivot by transfer data from rows to columns. Let us understand with an example.
- Create Student Table
CREATE TABLE Students ( Id INT PRIMARY KEY IDENTITY, [Student] VARCHAR(50), [Mathematics] INT, [Geography] INT, [Science] INT ) GO
- Insert Record To Student Table
INSERT INTO Students VALUES ('John', 78, 85, 91), ('Amit', 87, 90, 82)
- Before Applying Pivot Operator
SELECT * FROM Students
- Output
- After Applying The UnPivot Operator
SELECT [Student], [Subject], [Marks] FROM Students UNPIVOT ( [Marks] FOR [Subject] IN ([Mathematics], [Geography], [Science]) ) AS UnpivotTable
- Output
As you can see in the above figure, the Unpivot table has been created and we have converted the columns into distinct rows.
Conclusion
In this article, I have explained what is an Unpivot table in SQL and how to create one. I have also demonstrated a simple scenario in which I implement and use a pivot table.
Also, Check Pivot Table In SQL