SQL FOR XML Path 的用法

DECLARE @ProjectTempTable TABLE(BelongedTo VARCHAR(50),RecordNumber VARCHAR(50),UserName VARCHAR(50))
INSERT INTO @ProjectTempTable (BelongedTo,RecordNumber,UserName)
SELECT tmp.BelongedTo,tmp.RecordNumber,au.UserName FROM (
                SELECT aup.BelongedTo,aup.RecordNumber FROM dbo.App_UserInfo AS au
                LEFT  JOIN dbo.App_UserProInfo AS aup
                ON au.UserNumber = aup.UserNumber        
                WHERE au.UserCardID ='320882199206285699' AND (au.AccountTypes<>'' OR au.AccountTypes IS NOT NULL )
                ) AS tmp
                LEFT JOIN App_UserProInfo AS aup
                ON tmp.BelongedTo = aup.BelongedTo AND tmp.RecordNumber = aup.RecordNumber
                LEFT JOIN dbo.App_UserInfo AS au
                ON aup.UserNumber = au.UserNumber
                
SELECT * FROM @ProjectTempTable

上面查询的语句结果如下图:

现在要将 相同的BelongedTo,RecordNumber的UserName字段合并到一起去。

SELECT B.RecordNumber,B.BelongedTo,LEFT(StuList,LEN(StuList)-1) as UserName FROM (
SELECT BelongedTo,RecordNumber,
(SELECT UserName+',' FROM @ProjectTempTable 
  WHERE RecordNumber=A.RecordNumber AND BelongedTo=A.BelongedTo
  FOR XML PATH('')) AS StuList
FROM @ProjectTempTable A 
GROUP BY  RecordNumber,BelongedTo
) B 

查询结果如下图:

这里我声明了一个变量表,是为了下面的合并的时候看起简介点

 

posted @ 2016-09-09 13:20  管学文  阅读(1998)  评论(0编辑  收藏  举报