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
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.
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;
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, eg:
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:
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]
!)?
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.