Remove duplicates from return XQuery

倾然丶 夕夏残阳落幕 提交于 2020-08-07 06:51:32

问题


My XQuery is:

declare namespace xsd="http://www.w3.org/2001/XMLSchema"; 
for $schema in xsd:schema
for $nodes in $schema//*,
    $attr in $nodes/xsd:element/@name
where fn:contains($attr,'city')
return $attr

return: name="city" name="city" name="city" name="city" name="city"

When I add distinct-values like:

declare namespace xsd="http://www.w3.org/2001/XMLSchema"; 
for $schema in xsd:schema
for $nodes in $schema//*,
    $attr in $nodes/xsd:element/@name
where fn:contains($attr,'city')
return distinct-values($attr)

return: city city city city city

I need only one "city", how can I do it ?


回答1:


You need to apply the distinct-values function on the whole result (i. e., not to each single result item):

declare namespace xsd="http://www.w3.org/2001/XMLSchema"; 
distinct-values(
  for $schema in xsd:schema
  for $nodes in $schema//*,
      $attr in $nodes/xsd:element/@name
  where fn:contains($attr,'city')
  return $attr
)

The query can also be written as a single XPath expression:

distinct-values(//xs:element/@name[contains(., 'city')])



回答2:


Use group by. Your query returns multiple times city, because in each iteration (of the for loop) there is only one such element in $attr. So you are doing the distinct-values on a single element, but you are doing this multiple times.

declare namespace xsd="http://www.w3.org/2001/XMLSchema"; 
for $schema in xsd:schema
for $nodes in $schema//*,
    $attr in $nodes/xsd:element/@name
where fn:contains($attr,'city')
group by $attr
return $attr



回答3:


This work

distinct-values(for $schema in xsd:schema
for $nodes in $schema//*,
    $attr in $nodes/xsd:element/@name
where fn:contains($attr,'city')
return distinct-values($attr))


来源:https://stackoverflow.com/questions/16873753/remove-duplicates-from-return-xquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!