为每个唯一名称值连接不同的姓氏值

时间:2020-09-17 11:59:30

标签: sql-server string tsql group-by distinct

我要实现的是将每个DISTINCT名称值的所有DISTINCT姓氏值串联起来。

我所管理的是DISTINCT名称值的串联,但是不幸的是所有姓氏值。

下面是我的代码:

SELECT DISTINCT ST2.[Name], 
    SUBSTRING(
        (
            SELECT ','+ST1.Surname  AS [text()]
            FROM [Ext_Names] ST1
            WHERE ST1.[Name] = ST2.[Name]
            ORDER BY ST1.[Name]
            FOR XML PATH ('')
        ), 2, 1000) [Surname]
FROM [Ext_Names] ST2

样本数据

enter image description here

结果

enter image description here

所需的输出

enter image description here

2 个答案:

答案 0 :(得分:3)

您需要先选择不同的值,然后再进行汇总。如果您运行的是SQL Server 2017或更高版本,则可以使用string_agg()

select name, string_agg(surname, ',') within group (order by surname) surnames
from (select distinct name, surname from ext_names) t
group by name

答案 1 :(得分:0)

您可以做到这一点。

SELECT DISTINCT ST2.[Name], SUBSTRING((SELECT  ','+ T.Surename  AS [text()] FROM (SELECT DISTINCT ST1.Surename FROM Ext_Names ST1 WHERE ST1.Name = ST2.Name  ) T ORDER BY T.Surename FOR XML PATH('')),2,1000) [SureEname]
FROM Ext_Names ST2