Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

Column To Row (UNPIVOT)

From Wiki

Jump to: navigation, search

Row to column is a much more frequent request than column to row. SQL Server 2005 introduced UNPIVOT to help you accomplish this task. Before SQL Server 2005 the only way was to write a bunch of unioned select statements

Let's take a look at how this all works. create this table and the data

  1. CREATE TABLE #SomeTable
  2. (SomeID INT,Scarface INT,LOTR INT,Jaws INT,Blade INT,Saw INT)
  3.  
  4.  
  5. INSERT INTO #SomeTable VALUES (1,2,5,2,5,6)
  6. INSERT INTO #SomeTable VALUES (2,4,6,12,5,0)


This is what we have now

SomeIDScarfaceLOTRJawsSawBlade
125256
2461250


The output we need is this

1Blade5
2Blade5
1Jaws2
2Jaws12
1LOTR5
2LOTR6
1Saw6
2Saw2
1ScarFace2
2ScarFace4


SQL 2000 version by using union

  1. SELECT SomeID,'ScarFace' AS Movie,ScarFace AS Quantity
  2. FROM #SomeTable
  3. UNION ALL
  4. SELECT SomeID,'LOTR' AS Movie,LOTR AS Quantity
  5. FROM #SomeTable
  6. UNION ALL
  7. SELECT SomeID,'Jaws' AS Movie,Jaws AS Quantity
  8. FROM #SomeTable
  9. UNION ALL
  10. SELECT SomeID,'Blade' AS Movie,Blade AS Quantity
  11. FROM #SomeTable
  12. UNION ALL
  13. SELECT SomeID,'Saw' AS Movie,Saw AS Quantity
  14. FROM #SomeTable
  15. ORDER BY Movie,SomeID


SQL 2005/2008 version by using UNPIVOT

  1. SELECT SomeID, Movie, Quantity
  2. FROM
  3. (SELECT SomeID, Scarface, LOTR, Jaws, Saw,Blade
  4.  FROM #SomeTable) t
  5. UNPIVOT
  6. (Quantity FOR Movie IN
  7.     (Scarface, LOTR, Jaws, Saw,Blade)
  8. ) AS u
  9. ORDER BY Movie,SomeID


Here you can really see that you save a lot of code by using UNPIVOT over UNION


Contributed by: --SQLDenis 02:24, 31 May 2008 (GMT)


Part of SQL Server Programming Hacks

Section Sorting, Limiting Ranking, Transposing and Pivoting

280 Rating: 1.4/5 (7 votes cast)