问题背景
鉴于每个家庭的类别......
<?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>
我想要家庭最常见的类别......
<common-family-category id="3" count="2"/>
<common-family-category id="5" count="2"/>
成功尝试
我可以通过对每个迭代的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)}" />
并且通过迭代每个类别并将id存储在变量中......
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)}" />
尝试失败
但我无法通过迭代类别并直接将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)}" />
它在group by $family-category/@id
:
[XPST0003]在'group by'之后期待有效表达
问题
将$family-category/@id
设置为$family-category-id
并对其进行分组有效...
为什么直接按$family-category/@id
分组不起作用?
如果那真的不起作用,那是什么原因?
答案 0 :(得分:5)
基本上,XQuery 3.0中有两种形式的分组子句
一般表格是
group by $var := key-expression
其中$ var定义将引用该组的变量,key-expression是计算分组键的表达式。
如果你发现自己写作
group by $var := $var
然后你可以将它缩写为更方便的简写
group by $var
但你不能写
group by key-expression
不声明分组变量,除非在键表达式是简单变量引用的特殊情况下。