XQuery将节点值与Group By逻辑组合在一起

时间:2012-08-03 20:43:33

标签: sql-server xquery-sql

我正在寻找一个需要的XQuery:

<root>
    <entity>
        <entityid>1</entityid>
        <sometext>this is some text</sometext>
    </entity>
    <entity>
        <entityid>1</entityid>
        <sometext>this is some more text</sometext>
    </entity>
</root>

并制作一个记录集,如:

Entityid    sometext
1           this is some textthis is some more text

基本上,在由entityid分组时组合'sometext'节点中的值。我想我可以用循环完成这个,但不确定是否有更好的方法,可能有一个连接/组

2 个答案:

答案 0 :(得分:1)

declare @XML xml =
'<root>
    <entity>
        <entityid>1</entityid>
        <sometext>this is some text</sometext>
    </entity>
    <entity>
        <entityid>1</entityid>
        <sometext>this is some more text</sometext>
    </entity>
    <entity>
        <entityid>2</entityid>
        <sometext>Another entity</sometext>
    </entity>
</root>';

select T.entityid,
       @XML.query('/root/entity[entityid = sql:column("T.entityid")]/sometext').value('.', 'nvarchar(max)') as sometext
from (
     select distinct T.N.value('entityid[1]', 'int') as entityid
     from @XML.nodes('/root/entity') as T(N)
     ) as T;

结果:

entityid    sometext
----------- -----------------------------------------
1           this is some textthis is some more text
2           Another entity

答案 1 :(得分:1)

您也可以使用更基于XQuery的解决方案,例如

DECLARE @xml XML = '<root> 
    <entity> 
        <entityid>1</entityid> 
        <sometext>this is some text</sometext> 
    </entity> 
    <entity> 
        <entityid>1</entityid> 
        <sometext>this is some more text</sometext> 
    </entity> 
    <entity> 
        <entityid>2</entityid> 
        <sometext>Another entity</sometext> 
    </entity> 
</root>'

select 
    x.c.value('@entityId', 'int') entityId,
    x.c.value('.', 'varchar(max)') someText
from
    (
    select @xml.query('for $e in distinct-values(root/entity/entityid)
return <m entityId = "{$e}">{data(root/entity[entityid = $e]/sometext)}</m>')
    ) r(c)
    cross apply r.c.nodes('m') x(c)

感谢Mikael提供xml / extra方案。