2

Problem background

Given the categories from each family...

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <family>
        <categories>
            <cat id="1" />
            <cat id="2" />
        </categories>
    </family>
    <family>
        <categories>
            <cat id="3" />
            <cat id="5" />
        </categories>
    </family>
    <family>
        <categories>
            <cat id="3" />
            <cat id="5" />
            <cat id="6" />
        </categories>
    </family>
</root>

I want the categories that families have most in common...

<common-family-category id="3" count="2"/>
<common-family-category id="5" count="2"/>

Successful tries

I could achieve that result by grouping each iterated id...

for $family-category-id in //family/categories/cat/@id
count $return-indexes
group by $family-category-id
order by count($return-indexes) descending
where count($return-indexes) > 1
return
<common-family-category id="{$family-category-id}" count="{count($return-indexes)}" />

And also by iterating each category and storing the id in a variable...

for $family-category in //family/categories/cat
let $family-category-id := $family-category/@id
count $return-indexes
group by $family-category-id
order by count($return-indexes) descending
where count($return-indexes) > 1
return
<common-family-category id="{$family-category-id}" count="{count($return-indexes)}" />

Failed tries

But I couldn't achieve that by iterating the category and directly grouping the id...

for $family-category in //family/categories/cat
count $return-indexes
group by $family-category/@id
order by count($return-indexes) descending
where count($return-indexes) > 1
return
<common-family-category id="{$family-category/@id}" count="{count($return-indexes)}" />

It gives the following error in the group by $family-category/@id:

[XPST0003] Expecting valid expression after 'group by'

Question

Since setting $family-category/@id into $family-category-id and grouping it worked...

Why grouping by $family-category/@id directly doesn't work?

And if that really shouldn't work, what's the reason for that?

falsarella
  • 12,217
  • 9
  • 69
  • 115

1 Answers1

5

Essentially there are two forms of grouping clause in XQuery 3.0

The general form is

group by $var := key-expression

where $var defines the variable that will refer to the group, and key-expression is the expression that computes the grouping key.

If you find yourself writing

group by $var := $var

then you can abbreviate this to the more convenient shorthand

group by $var

But you can't write

group by key-expression

without declaring a grouping variable, except in the special case where the key expression is a simple variable reference.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164