[英]count element using Xquery and return the value
我的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>
它不断循环相同的数据,但不对其进行分组。 即使我使用不同的值,它仍然是相同的。 我的代码中有什么错误?
如果使用支持XQuery 3.0的XQuery处理器,您还可以group by
flwor语句利用该group by
:
for $book in /a/book
let $publisher := $book/pub
group by $publisher
return
<result>
<pub>{ $publisher }</pub>
<count>{ count($book) }</count>
</result>
分组使用distinct-values
。 您可以计算所有book
或pub
并仅过滤与当前迭代匹配的book
。
这个:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.