Description
The functx:avg-empty-is-zero function returns the average of the non-empty values in $values , over the number of nodes provided in $allNodes . This is useful for performing calculations where you want "missing" elements and/or attribute values to count as zero rather than not being included in the average at all.
Arguments and Return TypeName | Type | Description |
$values |
xs:anyAtomicType* |
the values to be averaged |
$allNodes |
node()* |
the sequence of all nodes to find the average over |
return value |
xs:double |
XQuery Function DeclarationSee XSLT definition. | declare namespace functx = "http://www.functx.com";
declare function functx:avg-empty-is-zero
( $values as xs:anyAtomicType* ,
$allNodes as node()* ) as xs:double {
if (empty($allNodes))
then 0
else sum($values[string(.) != '']) div count($allNodes)
} ; |
Exampleslet $in-xml := | <prices>
<price value="29.99" discount="10.00"/>
<price value="39.99" discount="6.00"/>
<price value="69.99"/>
<price value="49.99" discount=""/>
</prices> | return |
XQuery Example | Results | Explanation |
---|
functx:avg-empty-is-zero(
$in-xml//price/@discount, $in-xml//price) |
4 |
The average discount for the prices is 4, if you want the discount on the 3rd and 4th prices to be counted as zero. Using fn:avg($in-xml//price/@discount) function would have raised an error because the discount on the 4th price is not a valid number. If the 4th price did not have a discount attribute, it would return 8. |
See Alsofn:avg | The average of a sequence of values |
History |
Recommended Reading:
|