简体   繁体   中英

count element using Xquery and return the value

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?

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>

Grouping works using distinct-values . You can count all the book s or pub s and filter only the ones that match the current iteration.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM