Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 UnPivot a Pivoted SQL Table
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

2 Posts

Posted - 08/10/2008 :  17:03:46  Show Profile  Reply with Quote

Hi all... I'm new to this forum, and am a beginner to SQL querying.
Hopefully I can describe this in a way that makes sense.

There's a table I'm working with containing budgeting information that features a column for each month with a dollar amount.
I'd like to get a result set that has one line for each months amount.

Here's an example of the way it looks:

Travel Expenses, 2008, $1,500.00, $2,000.00, $2,500.00
Entertainment Expenses, 2008, $5,200.00, $5,350.00, $5,125.00

Here's an example of how I'd like my result set to look:

Travel Expenses, 2008, 9, $1,500.00
Travel Expenses, 2008, 10, $2,000.00
Travel Expenses, 2008, 11, $2,500.00
Entertainment Expenses, 2008, 9, $5,200.00
Entertainment Expenses, 2008, 10, $5,350.00
Entertainment Expenses, 2008, 11, $5,125.00

Can someone please help me form a SELECT statement that would do this? I'm guessing I have to use a CASE statement.
Thanks in advance from a frustrated beginnner :)

Flowing Fount of Yak Knowledge

7266 Posts

Posted - 08/10/2008 :  17:23:28  Show Profile  Reply with Quote
Sql2k5 has unpivot operator, read books online for details.
Go to Top of Page

Flowing Fount of Yak Knowledge

United Kingdom
1064 Posts

Posted - 08/10/2008 :  18:09:13  Show Profile  Reply with Quote
A practical example of unpivot:
Note Jeff points out that this is compensating for a design problem (first normal form violation). Ideally your schema should be normalised in the first place:
Go to Top of Page

Starting Member

2 Posts

Posted - 08/10/2008 :  20:07:24  Show Profile  Reply with Quote
Thank you both for the information.

pootle_flump.... Those links were exactly what I needed. Much appreciated.
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.04 seconds. Powered By: Snitz Forums 2000