PIVOT in SQL SERVER

One of the more complex statements that we can execute inside sql server is a PIVOT statement.

What it does? 

PIVOT statement allows us to convert what would normally be row data into column data.

Sounds Crazy…

In simply let’s imagine we have a table as follow.

fulltable

In above table years are in rows. Let’s suppose we want to get data by years. Now it’s time to use PIVOT. Using PIVOT we can convert years into columns.

PIVOT syntax

SELECT <NonPivot>
, <FirstPivotedColumn>
, …
FROM <Table containing data>
PIVOT (FUNCTION(<data column>)
FOR <List of pivoted columns>)
AS <alias>

Let’s do

SELECT * FROM @Table
PIVOT (SUM(Sales)
FOR [Year] IN([2010],[2012])
)AS pvt

The we get result

pivotedtable