If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > Microsoft SQL Server > Multiple rows combined based on a column

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 09-06-11, 13:32
dbi dbi is offline
Registered User
 
Join Date: Sep 2011
Posts: 1
Multiple rows combined based on a column

I have a table with two columns refid and name and it has the following values
1 tom
1 jim
2 bob
1 bob

I need a resultset that would have the following values
1 tom, jim, bob
2 bob

I have tried couple of things one being:
DECLARE @namelist VARCHAR(1000)
SELECT @namelist = COALESCE(@namelist +', ' ,'') + name FROM sales where refid = 1
SELECT @namelist
but i am looking for a resultset with a unique refid and all the names comma separated for that refid.

thanks,
dbi
Reply With Quote
  #2 (permalink)  
Old 11-20-11, 14:32
sqlserverdba1 sqlserverdba1 is offline
Registered User
 
Join Date: Oct 2011
Posts: 29
Use PIVOT and UNPIVOT feature of T-Sql

Using PIVOT and UNPIVOT
Reply With Quote
  #3 (permalink)  
Old 11-24-11, 05:51
homerow homerow is offline
Registered User
 
Join Date: Sep 2011
Location: Greenville, SC USA
Posts: 28
RE: Multiple rows combined based on a column

Code:
select
  r.refid
 ,stuff((select ', ' + name from sales where refid = r.refid for xml path('')),1,2,'') as namelist
from (select distinct refid from sales) r
Reply With Quote
Reply

Tags
join

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On