O'Reilly logo

Inside Microsoft® SQL Server® 2008: T-SQL Querying by Lubor Kollar Itzik Ben-Gan Dejan Sarka, and Steve Kass

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Unpivoting

Unpivoting is the opposite of pivoting—namely, rotating columns to rows. Unpivoting is usually used to normalize data, but it has other applications as well.

Note

Note

Unpivoting is not an exact inverse of pivoting—it won’t necessarily allow you to regenerate source rows that were pivoted. However, for the sake of simplicity, think of it as the opposite of pivoting.

In my examples, I’ll use the PvtCustOrders table, which you create and populate by running the following code:

USE tempdb; IF OBJECT_ID('dbo.PvtCustOrders') IS NOT NULL DROP TABLE dbo.PvtCustOrders; GO SELECT custid, COALESCE([2006], 0) AS [2006], COALESCE([2007], 0) AS [2007], COALESCE([2008], ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required