SQL Server UNPIVOT Query to Transpose Columns of a Table into Lines – C# Programming Example
SQL

SQL Server UNPIVOT Query to Transpose Columns of a Table into Lines

With SQL Server it is possible to Rotate columns in lines, to do this, it makes use the key word UNPIVOT. The syntax is special because it is not intuitive, this sample query transforms columns into rows of a SQL Server table. It is indeed useful to transpose the columns into rows for easier management, such as generic management of a field, and not management for each column.

Transforming columns of a table into rows with a UNPIVOT query

Creating the sample table to transpose with SQL Server

We start by creating the table used for our example. It has a column that contains the type of sales and a column for each month of the year.

Inserting a few lines to transpose in the table

We then insert the data into our table to rotate or transpose.

Writing the SQL query with the keyword UNPIVOT

We can now write the query UNPIVOT, in this example we pass the columns in lines. That is to say that for each type of sale and each month in columns, one obtains a created line.

Either 4 types of sales * 12 months = 48 lines transposed.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: