1

我正在寻找一个 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”节点中的值。我想我可能可以通过循环来完成此操作,但不确定是否有更好的方法,可能通过 join/group by

4

2 回答 2

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
于 2012-08-04T04:56:59.990 回答
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 / 额外场景。

于 2012-09-10T14:20:33.873 回答