码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-09-10 00:00:52      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:

思路:

自连接,使用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 NAMES
FROM 
        STUDENT T1
GROUP BY 
        T1.Team 

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

Team1                     Jack/Rose/Cindy
Team2                     Richard/Jenny

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

标签:

原文地址:http://www.cnblogs.com/wsion/p/5858247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!