Simple aggregation using xquery

S

Suma

I dont know xquery , so i was thinking someone in the forum will help
me out with this easy question

Suppose I have an instance document given below
<Root>
<Author Name='Alice' NumberOfBooks = '1'>
<Author Name='Bob' NumberOfBooks = '4'>
<Author Name='Collin' NumberOfBooks = '3'>
<Author Name='David' NumberOfBooks = '2'>
</Root>

Is there a way i can get the total number of books published by all
authors using a single xquery statement. (similiar to say SQL - select
sum(col) semantics)

What i DO NOT WANT to do is gettting all the nodes and doing the sum
at the client/my application. I would rather have the XML engine handle
the aggregation


Suma
 
S

SL

"Suma" a écrit :
I dont know xquery , so i was thinking someone in the forum will help
me out with this easy question

Suppose I have an instance document given below
<Root>
<Author Name='Alice' NumberOfBooks = '1'>
<Author Name='Bob' NumberOfBooks = '4'>
<Author Name='Collin' NumberOfBooks = '3'>
<Author Name='David' NumberOfBooks = '2'>
</Root>

Is there a way i can get the total number of books published by all
authors using a single xquery statement. (similiar to say SQL - select
sum(col) semantics)

sum(/Root/Author/@NumberOfBookds)
 
S

Suma

Great thanks
Now what if i need to do a aggregate over groups?
My repro was simpler than what i intend to do
<Root>
<Author ="Alice" Attrib="1">
<Author ="Alice" Attrib="2">
<Author ="Bob" Attrib="3">
<Author ="Bob" Attrib="4">
</Root>

I need to return
Alice 3
Bob 7
and
so on
Suma
 
S

SL

"Suma" a écrit :
Great thanks
Now what if i need to do a aggregate over groups?
My repro was simpler than what i intend to do
<Root>
<Author ="Alice" Attrib="1">
<Author ="Alice" Attrib="2">
<Author ="Bob" Attrib="3">
<Author ="Bob" Attrib="4">
^^^
This is not well-formed XML. I assume you have:
<Author name="Bob" Attrib="4">
^^^^
instead
I need to return
Alice 3
Bob 7
and
so on
Suma

It is an XPath issue :

sum(/Root/Author[@name='Alice']/@Attrib)

If you want to loop over all possible names, XQuery provide many
functionnalities, such as the so-called "Flower expression":

for $author in Book/Author/@name
return
<nbrOfBooks>{sum(/Root/Author[@name=$author]/@Attrib)}</nbrOfBooks>

(I havn't practiced XQuery for some time, and this is not tested!)
 
S

SL

Sorry:

- for $author in Book/Author/@name
+ for $author in /Book/Author/@name
return
- <nbrOfBooks>{sum(/Root/Author[@name=$author]/@Attrib)}</nbrOfBooks>
+ <nbrOfBooks>{sum(/Book/Author[@name=$author]/@Attrib)}</nbrOfBooks>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top