home contribute faq download

FunctX XQuery Functions

functx:avg-empty-is-zero

The average, counting "empty" values as zero

Google
Webdatypic.com

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 Type

NameTypeDescription
$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 Declaration

See 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)
 } ;

Examples

let $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 ExampleResultsExplanation
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 Also

fn:avgThe average of a sequence of values

History

Published OnLast UpdatedContributor(s)
2006-06-272007-02-26Priscilla Walmsley, Datypic, pwalmsley@datypic.com, https://www.datypic.com
Datypic XQuery Services

Recommended Reading:

XQuery