count元素,并返回值



我的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>

代码i使用:

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

它保持循环相同的数据,但不将其分组。即使我使用不同的值,它仍然是一样的。我的代码中有什么错误?

如果使用支持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>

分组使用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>

最新更新