Count values ​​obtained using a subscript function in XQuery

I have an XML file with the following data:

<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> 

Suppose I use a substring function to select the third character of the id attribute and assign it to the id variable:

  for $identifiers in file/unit/@id let $id := substring($identifiers, 3, 1) return ($id) 

Which returns the following:

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

I need an account for each unique value: in this case, 7 for "1" and 6 for "2". How to achieve this?

0
source share
2 answers

If your XQuery processor does not support group by , select all unique identifiers and count them yourself.

 let $ids := file/unit/@id/substring(., 3, 1) return for $uniqueID in distinct-values($ids) return element { "count" } { attribute { "id" } { $uniqueID }, count($ids[.=$uniqueID]) } 
+1
source

If you are using an XQuery 3.0 compatible processor (I tested using BaseX , use group by and count() :

 for $identifiers in file/unit/@id let $id := substring($identifiers, 3, 1) group by $id return element { "count" } { attribute { "id" } { $id }, count($identifiers) } 
+1
source

All Articles