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

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Haseeb Nomani

Author  Topic 

hnomani
Starting Member

35 Posts

Posted - 2004-10-15 : 11:41:08
There is a report I am working on where I need to change the data from a table where the row values will change into column name and all the data will be moved accordingly. I have created a simple example of what I need,

create table #test(state char(2), offer1 int, offer2 int, offer3 int)

insert into #test values ('NY', '70', '64', '34')
insert into #test values ('NJ', '64', '33', '18')
insert into #test values ('OH', '60', '31', '44')
insert into #test values ('PA', '62', '34', '27')

How would I write an SQL where the state values become a column name and data is rearranged. The final results should look like,

Results
type NY NJ OH PA
offer1 70 64 60 62
offer2 64 33 31 34
offer3 34 18 44 27

Please note that the number of rows can vary in the #test table (but will always be less than 100) and I would like to avoid hard coding the state values.

Thanks

dsdeming

479 Posts

Posted - 2004-10-15 : 13:47:48
Try searching this site for the word "pivot" or "pivot table". You should find code to do exactly what you need.

Dennis
Go to Top of Page

eyechart
Master Smack Fu Yak Hacker

3575 Posts

Posted - 2004-10-15 : 14:07:44
look for cross tab also

here is a good article on the subject: http://www.sqlteam.com/item.asp?ItemID=2955



-ec
Go to Top of Page
   

- Advertisement -