Welcome back to CodeYourCraft! Today, we're diving into XQuery Aggregate Functions. These powerful tools will help you analyze and manipulate your XML data in a breeze. Let's get started! š
XQuery Aggregate Functions are a set of functions used to perform calculations and generate summaries from XML data. They're similar to SQL's aggregate functions but designed specifically for XML.
š Note: XQuery Aggregate Functions can help you answer questions like:
Before we dive into specific functions, let's discuss the for, let, and order by clauses, which are essential when working with aggregate functions.
The for clause is used to loop through a sequence of nodes.
for $book in doc("books.xml")/books/bookThe let clause is used to create variables in XQuery.
let $totalPrice := 0
for $book in doc("books.xml")/books/book
let $price := $book/price
return $totalPrice + $priceThe order by clause is used to sort the sequence of nodes.
for $book in doc("books.xml")/books/book
order by $book/titleNow that we've covered the basics, let's explore some common XQuery Aggregate Functions.
The count() function returns the number of items in a sequence.
count(doc("books.xml")/books/book)The sum() function returns the sum of the values in a sequence.
let $totalPrice := 0
for $book in doc("books.xml")/books/book
let $price := $book/price
return $totalPrice + $priceThe avg() function returns the average of the values in a sequence.
let $totalPrice := 0
for $book in doc("books.xml")/books/book
let $price := $book/price
return $totalPrice + $price
return avg($totalPrice)The min() and max() functions return the minimum and maximum values in a sequence, respectively.
let $minPrice := 99999
for $book in doc("books.xml")/books/book
let $price := $book/price
if ($price < $minPrice) then $minPrice := $price
return $minPriceLet's analyze the number of books written by each author in a sample XML file.
books.xml
<books>
<book>
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<price>12.99</price>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<price>10.99</price>
</book>
<book>
<title>Of Mice and Men</title>
<author>John Steinbeck</author>
<price>9.99</price>
</book>
</books>for $author in distinct-values(doc("books.xml")/books/book/author)
let $bookCount := 0
for $book in doc("books.xml")/books/book[author=$author]
return
<author>{$author}</author>
<books>{$bookCount}</books>
let $bookCount := $bookCount + 1
return ()This example will produce the following output:
<author>Harper Lee</author>
<books>1</books>
<author>John Steinbeck</author>
<books>1</books>
<author>J.D. Salinger</author>
<books>1</books>š Note: The distinct-values() function is used to remove duplicate values.
What does the `count()` function do in XQuery?
What does the `sum()` function do in XQuery?
That's it for today's lesson on XQuery Aggregate Functions! Stay tuned for more tutorials at CodeYourCraft. Happy coding! š¤š