SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Rows to columns
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

shaggy
Posting Yak Master

India
228 Posts

Posted - 07/20/2012 :  09:00:20  Show Profile  Reply with Quote
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

India
228 Posts

Posted - 07/20/2012 :  09:14:07  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 07/20/2012 :  09:20:08  Show Profile  Reply with Quote
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

India
228 Posts

Posted - 07/20/2012 :  09:39:47  Show Profile  Reply with Quote
Thanks sunitabeck
Go to Top of Page
  Previous Topic Topic Next Topic  
 New 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.03 seconds. Powered By: Snitz Forums 2000