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.


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

FOR [Year] IN([2010],[2012])
)AS pvt

The we get result


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s