Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count element using Xquery and return the value

Tags:

xml

xquery

my xml data:

<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?

like image 496
user3664490 Avatar asked Jun 18 '26 14:06

user3664490


1 Answers

If using an XQuery 3.0 capable XQuery processor, you can also take advantage of the group by flwor statement:

for $book in /a/book
let $publisher := $book/pub
group by $publisher
return
  <result>
    <pub>{ $publisher }</pub>
    <count>{ count($book) }</count>
   </result>
like image 83
Jens Erat Avatar answered Jun 21 '26 07:06

Jens Erat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!