0

Consider a database with 3 tables holding names, with three rows:

names

ID,Name
1 , Eugene
2 , Igor
3 , George


rooms

ID, Roomnumber, Bednumber
1 , 10 , 1
1 , 15 , 1
1 , 10 , 2
2 , 5  , 1
2 , 3  , 1

Is there any way to get roomnumbers into single string with unique items only (can be separated by space or comma etc? So result will look something like this

ID, Name   , Roomnumbers
1 , Eugene , 10 15
2 , Igor   , 5  3
3 , George , 

I had no problem doing select from single table into same row, but I am having problem joining this tables together with distinc. Using samples that I found here the best I ever get is

ID, Name   , Roomnumbers
1 , Eugene , 10 10 15
2 , Igor   , 5  3
3 , George , 

The solution was

SELECT 
    distinct t1.ID, t1.Name, 
    SUBSTRING((SELECT ',' + CAST(t2.Roomnumber AS VARCHAR(10)) 
            FROM (SELECT DISTINCT ID, Roomnumber FROM Table2) t2
           WHERE t2.ID = t1.ID
            ORDER BY t2.ID, t2.Roomnumber
           FOR XML PATH ('')
       ), 2, 100) [Roomnumbers]
FROM Table1 t1

Thank you very much. I was trying to join and that was wrong and too complicated way to go around it. Thank you JPW

Cœur
  • 37,241
  • 25
  • 195
  • 267
syagin
  • 11
  • 1
  • http://stackoverflow.com/search?q=Concatenate+many+rows+into+a+single+text+string first one – Justin Sep 30 '14 at 07:17
  • there are many examples. Look for `FOR XML` – Darka Sep 30 '14 at 08:51
  • So basically I am back where I started and I have links to answer that I already used. Sadly none of them help me in my case but they allow me to get either 1 , 10 10 15 2 , 5 3 3 , but not joined tables. any idea where to look for that and what would be correct question in that case? – syagin Sep 30 '14 at 13:20
  • You need to use a derived table as source for the correlated subquery that eliminates duplicates. See this SQL Fiddle for a solution: http://www.sqlfiddle.com/#!3/11de6/1 As the question is closed I can't post this as an answer though. – jpw Sep 30 '14 at 13:44
  • That actually does look like what I am looking for. Let me try to actually get it to work (sadly of course this is only part of the bigger problem, but that seems like a right direction Thank you so much.) – syagin Sep 30 '14 at 14:13
  • @syagin this is adapted to your table names: http://www.sqlfiddle.com/#!3/3aa32/3 – jpw Sep 30 '14 at 14:14

0 Answers0