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:
<table>
<tr><th>Song Title</th><th>Score</th></tr>
{let $song := $words-sep//song
for $s in $song
let $word := $s/lyrics-counted/word
return (<tr><td>{$s/songName/string()}</td><td>{avg(
for $w in $word
return ($w/count/data() * $word-score//word[./v/string() = $w/v/string()]/vScore/data())
)}</td></tr>)
}
</table>
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.