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

时间:2018-07-10 09:20:14

标签: sql sql-server sql-server-2008-r2 aggregation

我不知道如何在标题中简短地描述我的问题,但我希望有人能够理解它并可以尝试帮助我:)

就我而言,我有2个表要加入:

=Parameters!ImagePath.Value + Fields!Photo.Value

结果:

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

目标:

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

有人有想法吗? 预先感谢您提供任何提示。

3 个答案:

答案 0 :(得分:4)

您可以通过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;

答案 1 :(得分:2)

可以使用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];

这假定每个“名称”都存在:

  • 仅在tblOne中;
  • 仅在tblTwo中;
  • 在tblOne和tblTwo中恰好一次。

如果以上逻辑不正确,那么您将需要XML版本。

此外,我只想说使用[Name][Group]之类的保留名称作为列名可能不是一个好主意(特别是[Group]!)?

答案 2 :(得分:1)

我相信您需要:

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;