Selecting Distinct Values

The distinct-values function selects distinct atomic values from a sequence. For example, the function call:

distinct-values(doc("catalog.xml")//product/@dept)

returns all the distinct values of the dept attribute, namely ("WMN", "ACC", "MEN"). This function determines whether two values are distinct based on their value equality using the eq operator.

It is also common to select a distinct set of combinations of values. For example, you might want to select all the distinct department/product number combinations from the product catalog. You cannot use the distinct-values function directly for this, because it accepts only one sequence of atomic values, not multiple sequences of multiple values. Instead, you could use the expression shown in Example 6-12.

Example 6-12. Distinctness on a combination of values

Query
let $prods := doc("catalog.xml")//product
for $d in distinct-values($prods/@dept),
    $n in distinct-values($prods[@dept = $d]/number)
return <result dept="{$d}" number="{$n}"/>
Results
<result dept="WMN" number="557"/>
<result dept="ACC" number="563"/>
<result dept="ACC" number="443"/>
<result dept="MEN" number="784"/>

For each distinct department, assigned to $d, it generates a list of distinct product numbers within that department using the predicate [@dept = $d]. It then returns the resulting combination of values as a result element. The order in which the values are returned is implementation-dependent, so it can be unpredictable.

Additional data ...

Get XQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.