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)
 ROWS TO COLUMNS WITH QUERY
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

comparin.fabio
Starting Member

Italy
3 Posts

Posted - 06/11/2012 :  13:24:44  Show Profile  Reply with Quote
QUERY CODE:
SELECT [B].[Id],
[I].[SN]
FROM Imballi] I
JOIN ImballiScatole] S ON S.Id = I.IdScatola
JOIN ImballiBancali] B ON B.Id = S.IdBancale
WHERE [S].[Id] = '3986'


RESULT:
ID SN
-- ------------
178 718218
178 718221
178 718217
178 718220
178 718223
178 718224
178 718226
178 718225
178 718219
178 718228
178 718227
178 718229

I need to retrieve all records to one row with a query

RESULT EXAMPLE:
ID SN1 SN2 SN3 SNX
-- ------ ------ ------ ------
178 718218 718221 718217 718220....

Many thanks to everyone!

CF

robvolk
Most Valuable Yak

USA
15557 Posts

Posted - 06/11/2012 :  13:35:46  Show Profile  Visit robvolk's Homepage  Reply with Quote
See here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=175651
Go to Top of Page

vinu.vijayan
Posting Yak Master

India
227 Posts

Posted - 06/12/2012 :  08:52:30  Show Profile  Reply with Quote
You can do a Dynamic Pivot to attain the Expected Result as follows:


--Creating table

Create Table Ex
(ID	int,
 SN int )


--Inserting Sample Data
 
Insert into Ex
Select 178,	718218
union ALL
Select 178,	718221	
union ALL
Select 178,	718217	
union ALL
Select 178,	718220	
union ALL
Select 178,	718223	
union ALL
Select 178,	718224	
union ALL
Select 178,	718226	
union ALL
Select 178,	718225	
union ALL
Select 178,	718219	
union ALL
Select 178,	718228
union ALL	
Select 178,	718227	
union ALL
Select 178,	718229


--Dynamic Pivot

Declare @cols varchar(max), @sql Varchar(max)
Select @cols = Coalesce(@cols + ', ', '') +QUOTENAME(rn) From
	(Select *, 'SN' + Cast(ROW_NUMBER() Over (Order By (Select NULL) ) AS Varchar(30) ) As rn From Ex) As a
Set @sql = 'Select Id, '+@cols+' From 
				(Select *, ''SN'' + Cast(ROW_NUMBER() Over (Order By (Select NULL) ) AS Varchar(30) ) As rn From Ex) As a
			Pivot
			(Max(SN) For rn IN ('+@cols+')) As pvt'
Execute (@sql)


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

comparin.fabio
Starting Member

Italy
3 Posts

Posted - 06/22/2012 :  13:46:40  Show Profile  Reply with Quote
Many thanks for help guys!

CF
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.05 seconds. Powered By: Snitz Forums 2000