Group XML Column Data
<p>Using SQL Server 2012. I have a table containing a group identifier and small snippets of XML. Here is a sample:</p>

<pre><code>CREATE TABLE temp (
    GroupId [int] NOT NULL,
    RawXml [xml] NULL
)

INSERT INTO temp VALUES (1, '&lt;Item&gt;&lt;Criteria Type="State" Values="CA"/&gt;&lt;Criteria Type="State" Values="TX"/&gt;&lt;Criteria Type="State" Values="FL"/&gt;&lt;/Item&gt;')
INSERT INTO temp VALUES (1, '&lt;Item&gt;&lt;Criteria Type="Manager" Values="Tim"/&gt;&lt;/Item&gt;')
INSERT INTO temp VALUES (2, '&lt;Item&gt;&lt;Criteria Type="Name" Values="Walters"/&gt;&lt;/Item&gt;')
INSERT INTO temp VALUES (2, '&lt;Item&gt;&lt;Criteria Type="Manager" Values="Tim"/&gt;&lt;/Item&gt;')
</code></pre>

<p>What I want to do is group the snippets of XML together by the GroupId to form a larger XML document so the end result is structured like this:</p>

<pre><code>&lt;Parent&gt;
    &lt;Group GroupId="1"&gt;
        &lt;Item&gt;
            &lt;Criteria Type="State" Values="CA"/&gt;
            &lt;Criteria Type="State" Values="TX"/&gt;
            &lt;Criteria Type="State" Values="FL"/&gt;
        &lt;/Item&gt;
        &lt;Item&gt;
            &lt;Criteria Type="Manager" Values="Tim"/&gt;
        &lt;/Item&gt;
    &lt;/Group&gt;
    &lt;Group GroupId="2"&gt;
        &lt;Item&gt;
            &lt;Criteria Type="Name" Values="Walters"/&gt;
        &lt;/Item&gt;
        &lt;Item&gt;
            &lt;Criteria Type="Manager" Values="Tim"/&gt;
        &lt;/Item&gt;
    &lt;/Group&gt;
&lt;/Parent&gt;
</code></pre>

<p>I fear the only solution is to concatenate the contents of the XML column first using some type of <a href="https://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string" title="string concatenation method">string concatenation method</a>, and then using a FOR XML select statement, but I feel this will be too slow for my application. Am I missing something and there is an easy way to group xml data in this manner, or is string concatenation my only choice.</p>