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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Multiple Rows into One Row
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

daniel50096230
Yak Posting Veteran

Malaysia
91 Posts

Posted - 05/28/2012 :  03:41:17  Show Profile  Reply with Quote
I has the following 4 rows,

Company_ID Value
S01 1
S01 2
S01 3


How can I make them into one row and 3 different columns? I don't want to combine them into one column but 3 different columns.

Thanks.

khtan
In (Som, Ni, Yak)

Singapore
16745 Posts

Posted - 05/28/2012 :  04:08:22  Show Profile  Reply with Quote

select	*
from	(
		select	Company_ID, Value, 
			col_no = row_number() over (partition by Company_ID order by Value)
		from	tbl
	) t
	pivot
	(
		max(Value)
		for	col_no in ([1], [2], [3])
	) p



KH
Time is always against us

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47040 Posts

Posted - 05/28/2012 :  14:05:03  Show Profile  Reply with Quote
what if there are more than three values? in such cases, what 3 values will you choose?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

vinu.vijayan
Posting Yak Master

India
227 Posts

Posted - 05/30/2012 :  02:49:30  Show Profile  Reply with Quote
You can do a Dynamic Pivot as follows:


--Creating Table

Create Table Ex
(Company_ID varchar(3),
 Value int)
 

--Inserting Sample Values
 
Insert Into Ex
Select 'S01', 1
Union ALL
Select 'S01', 2
Union ALL
Select 'S01', 3


--Dynamic Pivot

Declare @col varchar(max), @sql varchar(max)
Select @col = Coalesce(@col +', ','') + QUOTENAME(Value) From Ex
Set @sql = 'Select Company_Id, '+@col+' From Ex
			Pivot
			(max(Value) For Value In ('+@col+')) As pvt
			Order By Company_Id'
--Print @sql
Exec (@sql)


N 28° 33' 11.93148"
E 77° 14' 33.66384"
Go to Top of Page

madhivanan
Premature Yak Congratulator

India
22460 Posts

Posted - 05/30/2012 :  04:01:59  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
Also refer
http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

Madhivanan

Failing to plan is Planning to fail
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.06 seconds. Powered By: Snitz Forums 2000