How to perform multiple functions (distinct-values, count) on a variable in XQuery?

StackOverflow https://stackoverflow.com/questions/12406143

  •  01-07-2021
  •  | 
  •  

سؤال

I have an XML file with the following entries:

<file>
 <unit id="u-1.01"/>
 <unit id="u-1.02"/>
 <unit id="u-1.03"/>
 <unit id="u-1.04"/>
 <unit id="u-1.05"/>
 <unit id="u-1.06"/>
 <unit id="u-1.07"/>
 <unit id="u-2.01"/>
 <unit id="u-2.02"/>
 <unit id="u-2.03"/>
 <unit id="u-2.04"/>
 <unit id="u-2.05"/>
 <unit id="u-2.06"/>
</file>

I want to count the number of distinct-values using the query below.

The query goes through each of the @id attributes and selects the third character in the string.

declare function local:count-base-pages($basefile) {
for $identifiers in $basefile/unit/@id
let $id := distinct-values(substring($identifiers, 3, 1)) 
return count($id) 
};

However, this query returns the following sequence:

1 1 1 1 1 1 1 2 2 2 2 2 2

The wished outcome would be 2 because there are two distinct values: 1 and 2.

How am I misusing the distinct-values and count functions?

هل كانت مفيدة؟

المحلول

You need to wrap your functions around the actual FLWOR expression: count(distinct-values(for ... return ...))

نصائح أخرى

Use the shorter:

count(distinct-values(/*/*/@id/substring(.,3,1)))

Performing the above XQuery on the provided XML document:

<file>
 <unit id="u-1.01"/>
 <unit id="u-1.02"/>
 <unit id="u-1.03"/>
 <unit id="u-1.04"/>
 <unit id="u-1.05"/>
 <unit id="u-1.06"/>
 <unit id="u-1.07"/>
 <unit id="u-2.01"/>
 <unit id="u-2.02"/>
 <unit id="u-2.03"/>
 <unit id="u-2.04"/>
 <unit id="u-2.05"/>
 <unit id="u-2.06"/>
</file>

produces the wanted, correct result:

2
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top