title: XQuery: How do I use the results of an inner for-loop to order the results of an outer for-loop?
body: <p>I am writing an XQuery to process data pulled from two XML documents. The task is to take the words of a series of songs, assign a score to each word, and get the average word score for that song. So far, this works:</p>
  <pre><code>&lt;table&gt;
  &lt;tr&gt;&lt;th&gt;Song Title&lt;/th&gt;&lt;th&gt;Score&lt;/th&gt;&lt;/tr&gt;
  {let $song := $words-sep//song
  for $s in $song
       let $word := $s/lyrics-counted/word
       return (&lt;tr&gt;&lt;td&gt;{$s/songName/string()}&lt;/td&gt;&lt;td&gt;{avg(
            for $w in $word
            return ($w/count/data() * $word-score//word[./v/string() = $w/v/string()]/vScore/data())
  )}&lt;/td&gt;&lt;/tr&gt;)
  }
  &lt;/table&gt;
  </code></pre>
  <p>Here's the problem: I want to order the output of the songs (the outer for-loop) according to their score (which is only calculated in the inner for-loop). But the inner for-loop appears in the return of the outer for-loop, so I can't use order by in the outer for-loop since it would be ordering by a variable that hasn't been defined or calculated yet. Surely there must be a way to do this, but how? I'm running XPath 3.1 in oXygen, if that helps.</p>