SQL 加入的文本聚合 table

SQL Aggregation of text on joined table

请原谅缺乏正确的术语,我是一名专业软件工程师,通常与 Direct3D 框架打交道。我是自学数据库的。

我有一个 _People table 和一个 _Ethnicities table。由于人们可能有多个文化群体,因此我有 link table _linkPersonEthnicity。示例数据如下所示:

我要的是如下形式输出:

为了说明问题,我提出了以下(可运行的)查询:

select lPE.Person, Sum(E.ID) as SumOfIDs,
   Ethnicity = stuff(
      (select ', ' + Max(E.Name) as [text()]
        from _linkPersonEthnicity xPE
        where xPE.Person = lPE.Person
        for xml path('')
      ),
    1, 2, '')
from _Ethnicities E 
join _linkPersonEthnicity lPE on lPE.Ethnicity = E.ID
group by lPE.Person

它 returns 人的 ID,即为该人的种族找到的 ID 的总和,并用逗号连接最大值 Name。数据分组正确,SumOfIDs 有效,证明使用了正确的数据。

当然我想去掉 Max 聚合函数,但不能,因为它不在 group by 列表中。

有什么想法可以实现吗?

提前致谢,

上午


(非常感谢 Whosebug 上的其他答案让我走到这一步!特别是@Jonathan Leffler 的 explanation of the partitioning proceess and @Marc_s for illustrating a text concatenation technique。)

我也试过 coalesce 来自@Chris Shaffer

answer to concatenating strings
declare @Names VARCHAR(8000)
select @Names = COALESCE(@Names + ', ', '') + E.Name 
  from _Ethnicities E join _linkPersonEthnicity lPE on lPE.Ethnicity = E.ID
 where lPE.Person = 1001;
select @Names

同样的问题。如果我删除 where 并添加 group by,则无法访问文本字段 Name

如果我理解正确,你需要 join 在子查询中而不是在外部查询中

select lPE.Person, Sum(lpe.ethnicity) as SumOfIDs,
       Ethnicity = stuff((select ', ' + E.Name as [text()]
                          from _linkPersonEthnicity lPE2 join
                               _Ethnicities e
                               on lpe2.Ethnicity = e.id
                          where lpe2.Person = lPE.Person
                          for xml path('')
                         ), 1, 2, '')
from _linkPersonEthnicity lPE 
group by lPE.Person;

顺便问一下,你真的想要 ID 的总和还是计数?