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 2005 Forums
 Transact-SQL (2005)
 Query to change rows into columns and vice versa

Author  Topic 

miamikk
Starting Member

19 Posts

Posted - 2007-11-13 : 17:44:22
I would like to change rows into columns and columns to rows for the query output table

If the query output is like shown in the table below (including the column names in the first row).

A B C D E
a1 b1 c1 d1 e1
a2 b2 c2 d2 e2
a3 b3 c3 d3 e3
a4 b4 c4 d4 e4
a5 b5 c5 d5 e5

The table needs to be converted to (the rows become columns and columns become rows).

A a1 a2 a3 a4 a5
B b1 b2 b3 b4 b5
C c1 c2 c3 c4 c5
D d1 d2 d3 d4 d5
E e1 e2 e3 e4 e5


Thanks
KK

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-11-13 : 17:47:32
Have a look at the new UNPIVOT and PIVOT commands.



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

miamikk
Starting Member

19 Posts

Posted - 2007-11-14 : 07:48:09
Most of the examples I came across online using Pivot or crosstab are for summarizing the data. I just want a simple rearrange of rows and columns (transpose).

What I want to achive is shown in this link http://office.microsoft.com/en-us/excel/HP102245021033.aspx

This has to done on run time. The results of my query are stored in a temp table and at the end, I just use Select * from temp table to display results. I would like to transpose the temp table and would like to display the transposed table as final output.

I coped the query results in an excel sheet and done a simple transpose as shown in the image link below.

http://www.fiu.edu/~atmakurk/kk/query_output.JPG
Go to Top of Page

miamikk
Starting Member

19 Posts

Posted - 2007-11-14 : 07:55:47
quote:
Originally posted by Peso

Have a look at the new UNPIVOT and PIVOT commands.



I looked at this simple example http://msdn2.microsoft.com/en-us/library/ms177410.aspx and the Pivot is done a column that needs to be aggregated. I just want a simple pivot. I will try to work around with the example shown and see if I can figure out. But if some one provide a simple example that would help.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-11-14 : 08:57:24
PIVOTING is the same as summing one record.
But if you think there is a way around this, please let me know.

I know thousands of developers is waiting for ground-breaking news.




E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -