2

I don't know how to describe my problem shortly in the title but I hope someone will understand it and can try to help me :)

In my case I have 2 tables which I join:

SELECT t1.Name, t1.Group
FROM tblOne AS t1
UNION
SELECT t2.Name, t2.Group
FROM tblTwo AS t2

Result:

=====================
Name     |     Group
=====================
Miller   |     TST
Miller   |     DEV
Johnson  |     TST
White    |     TST
Lopez    |     DEV
Brown    |     TST
Jackson  |     DEV
Jackson  |     TST

Target:

Name     |     Group
=====================
Miller   |     DEV, TST
Johnson  |     TST
White    |     TST
Lopez    |     DEV
Brown    |     TST
Jackson  |     DEV, TST

Have someone an idea? Thanks in advance for any tip.

yuro
  • 2,189
  • 6
  • 40
  • 76
  • https://www.databasejournal.com/features/mssql/converting-comma-separated-value-to-rows-and-vice-versa-in-sql-server.html – Mani Deep Jul 10 '18 at 09:24
  • 1
    See [this](https://stackoverflow.com/a/31212160/9676724) – Ajay Gupta Jul 10 '18 at 09:24
  • Possible duplicate of [How Stuff and 'For Xml Path' work in Sql Server](https://stackoverflow.com/questions/31211506/how-stuff-and-for-xml-path-work-in-sql-server) – Mani Deep Jul 10 '18 at 09:25

3 Answers3

4

You can use pretty much simple xml method with stuff() function :

select t1.name, stuff((select distinct ','+t2.[group] 
                       from table2 t2
                       where t2.name = t1.name
                       for xml path('')
                       ), 1, 1, ''
                     ) as [group]
from table1 t1 
group by name;
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
2

You could use FOR XML but if your data is as it looks in your sample then you could also go for a much simpler query, e.g.:

SELECT 
    ISNULL(t1.[Name], t2.[Name]) AS [Name],
    ISNULL(t1.[Group] + CASE WHEN t2.[Group] IS NOT NULL THEN ',' ELSE '' END, '') 
        + ISNULL(t2.[Group], '') AS [Group]
FROM 
    tblOne AS t1
    FULL OUTER JOIN tblTwo AS t2 ON t2.[Name] = t1.[Name];

This assumes that each "Name" exists either:

  • only in tblOne;
  • only in tblTwo;
  • exactly once in tblOne and tblTwo.

If the above logic is incorrect then you would need the XML version instead.

Also, I just have to say that using reserved names like [Name] and [Group] as column names is probably a bad idea (particular [Group]!)?

Richard Hansell
  • 5,315
  • 1
  • 16
  • 35
1

I believe you need:

with t as (
      select t1.Name, Group as grp
      from tblOne
      union
      select t2.Name, Group as grp
      from tblTwo t2
     )
select name,
       stuff( (select ',' + grp
               from t t2
               where t2.name = t.name
               for xml path ('')
              ), 1, 1, ''
            ) as groups
from (select distinct name from t) t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786