We Can Pivot If You Want To

We Can Pivot If You Want To

We Can Pivot If You Want To 150 150 Carlos L Chacon

So I get that I am a little late to the party here; however, I find myself having to pivot from time to time and am always looking back for code as a refresher.  While Pivot is pretty cool, it always takes me a second to connect all the dots, so I hope this post helps do that.

Screen Shot 08-01-14 at 10.59 PMSo, with Pivot, we want to take data that looks like the data on the right–there are multiple rows for each ProductId and would like to get each product ID on one line with the quantities from each Bin.

 

 

When we are finished, the data will look like this.

Screen Shot 08-01-14 at 10.59 PM 001

One row for each Product ID

In my example, I am using the [Production].[ProductInventory] table in the adventureworks2012 database.  To make a row become columns, we must know ALL possible values we want to make as a column.  We specify these in the FOR line of the pivot syntax.  This query will create the columns for each value I specified in the Shelf column

[sourcecode language=”sql”]SELECT [ProductID],[A],[B],[C],[D],[E],[F],[G],[H],[I],[J],[K],[L]
FROM [Production].[ProductInventory]
PIVOT
(
SUM (Quantity)
FOR SHELF IN ([A],[B],[C],[D],[E],[F],[G],[H],[I],[J],[K],[L])
) AS PVT [/sourcecode]

Screen Shot 08-01-14 at 11.13 PMI should see something like this.  We are getting closer–we have our columns, but we still a line for each record.  We only want to see one line per product id.  This is where we put the columns we want from the table and the pivot syntax together in an almost sub-query like format and select the columns as we want them to display.

The syntax is something like this.  The first two rows are the columns I want, the second two are the columns I need from the table, and then add the pivot syntax followed by an order by and presto, you have your data the way you want it.

[sourcecode language=”sql”]SELECT [ProductID],[A],[B],[C],[D],[E],[F],[G],[H],[I],[J],[K],[L]
FROM
(SELECT [ProductID], Shelf, Quantity
FROM [Production].[ProductInventory]) p
PIVOT
(
SUM (Quantity)
FOR SHELF IN ([A],[B],[C],[D],[E],[F],[G],[H],[I],[J],[K],[L])
) AS PVT
ORDER BY [ProductID]
[/sourcecode]

Imagine what’s possible with a dedicated SQL specialist on your team.

Leave a Reply

Back to top