T-SQL Concatenate&将多行分组为一行

时间:2017-08-15 15:36:03

标签: sql-server tsql

我正在寻找一种分组的方法,同时也将行连接成逗号分隔的字符串。 例如:

Name            Place
Steve Jones     New York
Steve Jones     Washington
Albert Smith    Miami
Albert Smith    Denver

到...

Steve Jones    New York, Washington
Albert Smith   Miami, Denver

非常感谢

4 个答案:

答案 0 :(得分:3)

如果您使用SQL Server 2008及更高版本,则可以使用STUFF和XML PATH来获得所需的结果。

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    Actor.isHigherJump=false;
    return false;
}

答案 1 :(得分:0)

如果您使用2017,则可以使用String_Agg,SQL Azure,您可以查询如下:

C

答案 2 :(得分: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 Demo

如果PeoplePlaces实际上是具有各自键的单独表格,那么我们可以简单地进行一些。

答案 3 :(得分:0)

使用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)