简体   繁体   English

如何在一列中连接值? (SQL Server 2008R2)

[英]How to join values in one column? (SQL Server 2008R2)

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: 在我的情况下,我加入了2个表:

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. 提前感谢任何提示。

You can use pretty much simple xml method with stuff() function : 你可以使用非常简单的xml方法和stuff()函数:

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: 可以使用FOR XML但如果您的数据与样本中的数据相同,那么您还可以进行更简单的查询,例如:

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; 只在tblOne;
  • only in tblTwo; 只在tblTwo;
  • exactly once in tblOne and tblTwo. 在tblOne和tblTwo中只有一次。

If the above logic is incorrect then you would need the XML version instead. 如果上述逻辑不正确,那么您将需要XML版本。

Also, I just have to say that using reserved names like [Name] and [Group] as column names is probably a bad idea (particular [Group] !)? 另外,我只是说使用[Name][Group]类的保留名称作为列名可能是一个坏主意(特别是[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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM