Reverse PIVOT or UNPIVOT in SQL Server
Reversing the already pivoted table is called Reverse PIVOT which is done using UNPIVOT. For example, the above table can be brought to its original form using UNPIVOT operator.
Syntax:
SELECT . . .
FROM (
SELECT . . .
FROM
<Table Name>
) AS SourceTable
UNPIVOT (
<Column Name> FOR <Pivoted Column> IN (<Pivoted Column Values...>)
) AS UnpivotedTable;
Explanation of Syntax:
- <Column name> is the column that gets its values from the Pivoted columns.
- <Pivoted Column> is the column on which the PIVOT works.
- <Pivoted Column Values…> is the list of values of Columns which where pivoted.
Reverse PIVOT Table in SQL Server
In SQL Server, the PIVOT operation is a powerful feature that allows you to transform rows into columns, providing a convenient way to structure and analyze data. However, there are situations where we may need to reverse this operation, converting columns back into rows. This process is commonly known as “unpivoting” or “reverse PIVOT”. The UNPIVOT
operator in SQL Server performs the reversal of the PIVOT operation. In this article, we will learn bout PIVOT and UNPIVOT in detail along with its syntax, practical examples and so on.