count元素使用Xquery并返回值

时间:2014-06-08 15:42:37

标签: xml xquery

我的xml数据:

<a>
   <book>
        <pub>John</pub>
   </book>
   <book>
        <pub>John</pub>
    </book>
    <book>
         <pub>Mary</pub>
    </book>
</a>

所以我想计算每个的数字并显示它们

预期产出:

 <result>
         <pub>John</pub>
         <total>2</total>
 </result>
 <result>
         <pub>Mary</pub>
         <total>1</total>
  </result>

但是我的输出:

 <result>
         <pub>John</pub>
         <total>1</total>
 </result>
<result>
         <pub>John</pub>
         <total>1</total>
 </result>
 <result>
         <pub>Mary</pub>
         <total>1</total>
  </result>

代码我使用:

for $b in /a/book
let $count := count($b/pub)
for $pub in $b/pub
return
     <result> {$pub} <total>{$count}</total></result>

它继续循环相同的数据但不对其进行分组。即使我使用不同的值,它仍然相同。我的代码中有什么错误?

2 个答案:

答案 0 :(得分:2)

如果使用支持XQuery 3.0的XQuery处理器,您还可以利用group by flwor语句:

for $book in /a/book
let $publisher := $book/pub
group by $publisher
return
  <result>
    <pub>{ $publisher }</pub>
    <count>{ count($book) }</count>
   </result>

答案 1 :(得分:1)

使用distinct-values进行分组工作。您可以对所有bookpub进行计数,并仅过滤与当前迭代匹配的那些。

此:

let $b := /a/book/pub
  for $pub in distinct-values($b)
      let $count := count($b[. eq $pub])
      return <result>
                <pub>{$pub}</pub> 
                <total>{$count}</total>
             </result>

将产生:

<result>
   <pub>John</pub>
   <total>2</total>
</result>
<result>
   <pub>Mary</pub>
   <total>1</total>
</result>