PIVOT and UNPIVOT Operators in SQL Server(TSQL)

The PIVOT , which is indispensable for Excel users, can be implemented with SQL Server 2005 via T-SQL. But I can’t say it’s as talented as Excel.

Consider the following ORDER table.

First, let’s find the total sales of the products according to years with classsic methods:

Let’s do the same with PIVOT:

We are creating a table for only the relevant columns. It can also be a Temp table.

Or, without creating a temporary table, we can read the columns directly from the Order Table with subquery.

Likewise, we can change the position of columns and rows using the UNPIVOT.

Ahmet KAYMAZ
Author: Ahmet KAYMAZ

Leave a Reply

Your email address will not be published. Required fields are marked *