[英]count element using Xquery and return the value
my xml data: 我的xml数据:
<a>
<book>
<pub>John</pub>
</book>
<book>
<pub>John</pub>
</book>
<book>
<pub>Mary</pub>
</book>
</a>
So i want to count number for each and display them 所以我想计算每个的数字并显示它们
Expected output: 预期产量:
<result>
<pub>John</pub>
<total>2</total>
</result>
<result>
<pub>Mary</pub>
<total>1</total>
</result>
But my output: 但我的输出:
<result>
<pub>John</pub>
<total>1</total>
</result>
<result>
<pub>John</pub>
<total>1</total>
</result>
<result>
<pub>Mary</pub>
<total>1</total>
</result>
code i using : 代码我使用:
for $b in /a/book
let $count := count($b/pub)
for $pub in $b/pub
return
<result> {$pub} <total>{$count}</total></result>
it keep looping the same data but not group it . 它不断循环相同的数据,但不对其进行分组。 even i use distinct-values it's still same.
即使我使用不同的值,它仍然是相同的。 what error in my code?
我的代码中有什么错误?
If using an XQuery 3.0 capable XQuery processor, you can also take advantage of the group by
flwor statement: 如果使用支持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>
Grouping works using distinct-values
. 分组使用
distinct-values
。 You can count all the book
s or pub
s and filter only the ones that match the current iteration. 您可以计算所有
book
或pub
并仅过滤与当前迭代匹配的book
。
This: 这个:
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>
will produce: 将产生:
<result>
<pub>John</pub>
<total>2</total>
</result>
<result>
<pub>Mary</pub>
<total>1</total>
</result>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.