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
 General SQL Server Forums
 New to SQL Server Programming
 Rows to columns

Author  Topic 

shaggy
Posting Yak Master

248 Posts

Posted - 2012-07-20 : 09:00:20
This is a sample table. I want to transform data from rows to column
Can anybody help me in this
create table #t1(col2 varchar(100))

insert #t1 select 'A'
insert #t1 select 'B'
insert #t1 select 'C'

I want resultset to be

COL1 Col2 COL3
A B C

shaggy
Posting Yak Master

248 Posts

Posted - 2012-07-20 : 09:14:07
I tried this its working.
create table #t1(col1 int identity ,col2 as 'a'+convert(varchar,col1) )
insert #t1 default values
select MAX(case when col1 = 1 then col2 end),MAX(case when col1 = 3 then col2 end),MAX(case when col1 = 3 then col2 end) from #t1

I want to know, is there any other methods
Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-07-20 : 09:20:08
On SQL 2005 or later, you can use PIVOT operator like this:
SELECT
*
FROM
#t1
PIVOT
( MAX(col2) FOR col1 IN ([1],[2],[3]))P
That obviously is not scalable. WHen there are unknown number of columns to pivot, people use DYNAMIC PIVOT - see Madhivanan's blog here: http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx
Go to Top of Page

shaggy
Posting Yak Master

248 Posts

Posted - 2012-07-20 : 09:39:47
Thanks sunitabeck
Go to Top of Page
   

- Advertisement -