T-SQL连接多行并将它们分组为单个行

4
我正在寻找一种方法,在分组的同时将行连接成逗号分隔的字符串。 例如:
Name            Place
Steve Jones     New York
Steve Jones     Washington
Albert Smith    Miami
Albert Smith    Denver

to ...

Steve Jones    New York, Washington
Albert Smith   Miami, Denver

非常感谢。

@Muguel TSQL 不是 MySQL 使用的语言。 - Hogan
这通常在显示层(网页、报告、应用程序等)比在SQL中要容易得多。虽然有可能,但TSQL没有清晰的语法来进行字符串聚合。 - D Stanley
4个回答

7
如果您使用 SQL Server 2008 或更高版本,可以使用 STUFF 和 XML PATH 来获取所需结果。
SELECT DISTINCT Name
    , STUFF((
        SELECT ',' + Place
        FROM YourTable t1
        where t1.Name = t2.Name
        FOR XML PATH('')
    ), 1, 1, '') AS Places
FROM YourTable t2

1

使用CROSS APPLY和FOR XML PATH:

SELECT distinct PP.Name, SUBSTRING(A.Places, 0, LEN(A.Places)) AS CombinedPlaces
FROM PersonPlace PP
CROSS APPLY 
(
    SELECT place + ', ' 
    FROM PersonPlace AS AP
    WHERE AP.Name = PP.Name
    FOR XML PATH('')        
) A(places) 

0

如果你使用的是2017或SQL Azure,你可以使用String_Agg函数。否则,你可以按照以下方式查询:

Select [Name],
    Places = Stuff((Select ', '+Place from yourtable where [Name] = t.[Name] for xml path('')),1,2,'')
    from yourtable
    group by [Name]

0

可能有更简单的方法,但这个也可以:

with N as
(
    select name, count(*) over (partition by name order by name) c from PersonPlace
),

Q as
(
    select J.name, J.place, cast(J.place as varchar) place_name, J.c cnt, 1 c from
        (select distinct(name) from PersonPlace) K
            cross apply
            (
                select top 1 P.*, N.c from PersonPlace P
                    inner join N on N.name = P.name

                where P.name = K.name
            ) J

    union all
        select P.name, P.place, cast(Q.place + ', ' + P.place as varchar), Q.cnt, Q.c + 1  

             from PersonPlace P 
                inner join Q on Q.name = P.name and Q.c + 1 <= cnt and P.place <> Q.place

)

select Q.name, Q.place_name from Q where Q.c  = Q.cnt

结果:

name            place_name
--------------  ----------------------
Steve Jones     New York, Washington  
Albert Smith    Denver, Miami         

Rextest演示

如果PeoplePlaces实际上是具有自己的键的单独表格,那么我们可以简单地做很多事情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接