I have a table that is rather wide that I would like to convert to tall. The data currently resides like this:
VEND YEAR I1_DOLS I1_QTY I2_DOLS I2_QTY I3_DOLS I3_QTY ...
1234 2011 101587 508 203345 334 105938 257
1234 2012 257843 587 235883 247 178475 456
1011 2010 584737 432 587274 356 175737 563
1011 2011 517774 356 483858 456 481785 354
I would like to convert this to a table that looks like this:
VEND YEAR MONTH DOLS QTY
1234 2011 1 101587 508
1234 2011 2 203345 334
1234 2011 3 105938 257
1234 2012 1 257843 587
1234 2012 2 235883 247
.
.
.
I assume that a PIVOT is what I need, but I can't seem to figure this out.
You can unpivot the data using
CROSS APPLY (VALUES)
. Here is an article to explain how this is done:http://www.sqlservercentral.com/articles/CROSS+APPLY+VALUES+UNPIVOT/91234/
Basically the code is:
See SQL Fiddle with Demo
Or you could use a
UNION ALL
query:See SQL Fiddle with Demo
Or you can even apply both the
UNPIVOT
and thePIVOT
function to transform the data:See SQL Fiddle with Demo.
All three will give the same result: