使用XQuery计算平均值

时间:2015-04-01 15:58:53

标签: xquery

我需要使用XQuery计算每门课程的平均值。

这是XML代码:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<?xml-stylesheet href="class.xsl" type="text/xsl" ?>
<university>
<student><sname>Charlie Parker</name>
<course sigle="INF8430" note="69" />
<course sigle="INF1030" note="65" />
<course sigle="INF1230" note="73" /></student>
<student><name>Miles Davis</name>
<course sigle="INF8430" note="65" />
<course sigle="INF1030" note="77" />
<course sigle="INF1230" note="83" /></student>
<student><name>John Coltrane</name>
<course sigle="INF9430" note="24" />
<course sigle="INF1030" note="64" />
<course sigle="INF1230" note="56" /></student>
<student><name>Charles Mingus</name>
<course sigle="INF8430" note="34" />
<course sigle="INF1230" note="89" /></student>
</university>

输出文件应如下所示:

<list>
<course sigle="INF8430">85</course>
<course sigle="INF1030">76.66666666666667</course>
<course sigle="INF1230">81.5</course>
<course sigle="INF9430">39</course>
</list>

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

element list {
  let $courses := doc('mydoc.xml')/university/student/course
  for $id in distinct-values($courses/@sigle)
  let $values := $courses[@sigle = $id]/xs:double(@note)
  return element course {
    attribute sigle { $id },
    fn:avg($values)
  }
}