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?

4

1 回答 1

5

在 XQuery 3.0 中有两种形式的分组子句

一般形式是

group by $var := key-expression

其中 $var 定义将引用组的变量,而 key-expression 是计算分组键的表达式。

如果你发现自己在写作

group by $var := $var

那么您可以将其缩写为更方便的速记

group by $var

但你不能写

group by key-expression

不声明分组变量,除非在键表达式是简单变量引用的特殊情况下。

于 2014-08-23T09:21:43.263 回答