views:

44

answers:

3

I have data that looks like this

Investor    Contact
IBM           James  
IBM           Dean  
IBM           Sean  
Microsoft     Bill  
Microsoft     Steve

I need the data to look like this

Investor     Contact
IBM          James,Dean,Sean  
Microsoft    Bill,Steve  

OR if the above is impossible

Investor        Contact1  Contact2   Contact3  ...
IBM             James      Dean        Sean  
Microsoft        Bill      Steve
+2  A: 

Try the method below to get your comma separated list going. I'm going to have to play with it some more to figure out how to get the grouping working.

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + Contact
FROM InvestorContact
SELECT @listStr
Abe Miessler
Any more with this? I'd love to see some more about how this fits with grouping. Thanks!
Ehsan
+3  A: 

This should work:

SELECT Investor, 
STUFF((
    SELECT ',' + convert(nvarchar(50), Contact) 
    FROM Investors I2
    WHERE I2.Investor = I1.Investor
    FOR XML PATH('')
), 1, 1, '') Contacts
FROM Investors I1
GROUP BY Investor

And result in:

IBM       James,Dean,Sean
Microsoft   Bill,Steve
LittleBobbyTables
Amazing but how does it work?! Any chance you could explain this. I don't want to copy paste...ya know?
Ehsan
I think this article covers it better than I could: http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/. Basically, XML PATH merges the strings together, and then STUFF trims off the leading comma.
LittleBobbyTables
On second thoughts, looking closer at this my row seems to have duplicated a lot of the contacts. So it says Joe, Billy, James, Joe, Billy James, etc. Any thoughts?
Ehsan
Subtree cost of 0.0179763
OMG Ponies
I added select distinct in the inner select...seems to fixed that issue. Still verifying the data. Will post as Answer once I've checked 100%. Thanks for your help!
Ehsan
+2  A: 

Just in case any of your contacts have special XML characters in their names: the Tony Rogerson approach.

;with data as
(
SELECT 'IBM' Investor,  'James' Contact UNION ALL  
SELECT 'IBM' ,          'Dean'  Contact UNION ALL  
SELECT 'IBM' ,          'Sean'  Contact UNION ALL  
SELECT 'Microsoft' ,    'Bill'  Contact UNION ALL    
SELECT 'Microsoft',     'Steve' Contact
)
SELECT Investor, 
   stuff((SELECT mydata
   FROM (
      SELECT ',' + Contact  AS [data()]
      FROM
      data AS d2
      WHERE d2.Investor = d1.Investor
      FOR XML PATH(''), TYPE
   ) AS d ( mydata ) FOR XML RAW, TYPE ).value( '/row[1]/mydata[1]', 'varchar(max)' )
, 1, 1, '')
FROM data d1
GROUP BY Investor
Martin Smith
The subtree cost when I test with a table is atrocious - 2.49187
OMG Ponies
Martin Smith
Yeah, `FOR XML PATH` does have the issue with special characters.
OMG Ponies