首页 > 代码库 > T-SQL 合并多行数据显示到一行

T-SQL 合并多行数据显示到一行

思路:

自连接,使用For XML Path(‘‘)和STUFF函数

SELECT * FROM STUDENT

Name                      Team
------------------------- -------------------------
Jack                      Team1
Rose                      Team1
Cindy                     Team1
Richard                   Team2
Jenny                     Team2

 

SELECT        T1.Team,        STUFF((                SELECT                     CONCAT(/,T2.Name)                FROM                        STUDENT T2                WHERE                         T2.Team=T1.Team                FOR XML PATH(‘‘)            ),1,1,‘‘)        AS NAMESFROM         STUDENT T1GROUP BY         T1.Team 

Team                      NAMES
------------------------- ---------------------------------------------------------

Team1                     Jack/Rose/Cindy
Team2                     Richard/Jenny

T-SQL 合并多行数据显示到一行