SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Lots of ways to UNPIVOT a table

I recently read an awesome post on http://www.stackexchange.com questioning how to change columns to rows ie UNPIVOT. One answer demonstrated 4 different ways to unpivot a table including your basic UNPIVOT statement, CROSS APPLY, CROSS APPLY with VALUES and a dynamic SQL version for when you have a large number of columns.

The second answer demonstrated how to do the UNPIVOT using XQuery. The XQuery method also lets you UNPIVOT a large number of columns without naming them explicitly. There was a lot of discussion as to the pros and cons to this method in the comments, but I’m a firm believer in knowing all the methods you can (and all of the pros and cons) regardless of whether or not you plan on using them.

Now if only I could find as good a list of multiple method’s for PIVOTing a table.

Filed under: Microsoft SQL Server, SQLServerPedia Syndication, T-SQL Tagged: code language, CROSS APPLY, language sql, microsoft sql server, sql statements, T-SQL


My name is Kenneth Fisher and I am Senior DBA for a large (multi-national) insurance company. I have been working with databases for over 20 years starting with Clarion and Foxpro. I’ve been working with SQL Server for 12 years but have only really started “studying” the subject for the last 3. I don’t have any real "specialities" but I enjoy trouble shooting and teaching. Thus far I’ve earned by MCITP Database Administrator 2008, MCTS Database Administrator 2005, and MCTS Database Developer 2008. I’m currently studying for my MCITP Database Developer 2008 and should start in on the 2012 exams next year. My blog is at www.sqlstudies.com.


Leave a comment on the original post [sqlstudies.com, opens in a new window]

Loading comments...