Jeff D
Jeff D

Reputation: 13

XQuery 1.0 - setting a maximum value

Using Xquery 1.0, here is a small sample of the data that I'm working with:

<countries>
  <country name="Afghanistan" population="22664136" area="647500">
    <language percentage="11">Turkic</language>
    <language percentage="35">Pashtu</language>
    <language percentage="50">Afghan Persian</language>
  </country>
  <country name="Albania" population="3249136" area="28750"/>
  <country name="Algeria" population="29183032" area="2381740">
    <city>
      <name>Algiers</name>
      <population>1507241</population>
    </city>
  </country>
  <country name="American Samoa" population="59566" area="199"/>
  <country name="Andorra" population="72766" area="450"/>
  <country name="Angola" population="10342899" area="1246700"/>
  <country name="Anguilla" population="10424" area="91">
    <language percentage="100">English</language>

I'm trying to find the maximum Percentage attribute for each Language sub-element. After many tries, I noticed an issue.

Using the following query:

for $distinct_language in distinct-values(doc("countries.xml")/countries/country/language)
let $max := max(doc("countries.xml")/countries/country[language = $distinct_language]/language/@percentage)
return <Language_Max language="{$distinct_language}"> {$max} </Language_Max>

a small sample of the result is:

<Language_Max language="Turkic">50</Language_Max>
<Language_Max language="Pashtu">50</Language_Max>
<Language_Max language="Afghan Persian">50</Language_Max>
<Language_Max language="English">100</Language_Max>

Using just "Turkic" language as an example, I'm expecting:

<Language_Max language="Turkic">11</Language_Max>

I think the issue is when I set the $max variable, based on the predicate, it looks for a Country that CONTAINS "Turkic" as a Language (in this case the Country is Afghanistan), and then gets Maximum percentage from any of that Country's Languages (which is 50 from the "Afghan Persian" Language).

How can I return the maximum Percentage attribute for each Language and NOT the maximum Percentage of all of that Country's Languages?

I hope that made sense, and any assistance is appreciated!

Upvotes: 1

Views: 156

Answers (1)

Christian Gr&#252;n
Christian Gr&#252;n

Reputation: 6229

You’ll need to move the predicate one level down and filter the language instead of the country. Here is one way to do it (I bound the languages to an additional variable, as the same data will be accessed twice):

let $languages := doc('countries.xml')/countries/country/language
for $language in distinct-values($languages)
let $max := max($languages[. = $language]/@percentage)
return <Language_Max language="{ $language }">{ $max }</Language_Max>

Upvotes: 1

Related Questions