如何在GROUP BY操作中聚合XML片段

时间:2017-07-20 12:32:36

标签: sql sql-server xml group-by

我正在使用包含XML代码段的一些行。

我当前状态的行看起来像这样:

TeamId     Player
----------------------------------------------------------------------------
1   |  <Player><FirstName>Bob</FirstName><LastName>Smith</LastName></Player>
1   |  <Player><FirstName>Sam</FirstName><LastName>Jones</LastName></Player>
2   |  <Player><FirstName>David</FirstName><LastName>White</LastName></Player>
2   |  <Player><FirstName>James</FirstName><LastName>Black</LastName></Player>

使用我的查询,我希望按TeamId对行进行分组,并将这些XML片段聚合到父<Players>元素中,因此输出将如下所示:

1   | <Players>
        <Player><FirstName>Bob</FirstName><LastName>Smith</LastName></Player>
        <Player><FirstName>Sam</FirstName><LastName>Jones</LastName></Player>
      </Players>  
2   | <Players>
        <Player><FirstName>David</FirstName><LastName>White</LastName></Player>
        <Player><FirstName>James</FirstName><LastName>Black</LastName></Player>
      </Players>

我该怎么做? 非常感谢!

2 个答案:

答案 0 :(得分:4)

我试过这样的

CREATE TABLE #A
    (
    TEAMID INT,
    PLAYER XML 
    )
    INSERT INTO #A VALUES
    (1,'<PLAYER><FIRSTNAME>BOB</FIRSTNAME><LASTNAME>SMITH</LASTNAME></PLAYER>'),
    (1,'<PLAYER><FIRSTNAME>SAM</FIRSTNAME><LASTNAME>JONES</LASTNAME></PLAYER>'),
    (2,'<PLAYER><FIRSTNAME>DAVID</FIRSTNAME><LASTNAME>WHITE</LASTNAME></PLAYER>'),
    (2,'<PLAYER><FIRSTNAME>JAMES</FIRSTNAME><LASTNAME>BLACK</LASTNAME></PLAYER>')


SELECT  T.TEAMID,
        (   SELECT  TEAMID ,
                    PLAYER
            FROM    #A AS X
            WHERE X.TeamId = T.TeamId
            FOR XML PATH('PLAYER'), TYPE, ROOT('PLAYERS')

        ) AS XML_FORMAT_STRING
FROM    #A AS T
GROUP BY T.TEAMID;

答案 1 :(得分:1)

尝试这样

SELECT  tbl.TeamId,
        (   SELECT Player AS [*]
            FROM   YourTable AS X
            WHERE X.TeamId = tbl.TeamId
            FOR XML PATH(''), TYPE, ROOT('Players')
        ) AS [*]
FROM    YourTable AS tbl
GROUP BY tbl.TeamId;

别名AS [*]告诉引擎按原样插入给定元素 。这可以避免额外的名称级别。空PATH('')也可以避免额外的名称级别。