XQuery基于不同子元素的子元素的平均值

时间:2014-11-07 20:39:10

标签: database xquery saxon

所以我在使用avg函数在XQuery中按照我想要的方式工作时遇到了一些麻烦。我有一个学生的XML文件,他们有GPA和分类(新生,大二,初级,高级)。我想找到每个分类的平均GPA。我首先得到不同的分类。然后,我获得所有学生的列表,并在学生分类=不同分类时选择平均GPA。这将返回4个平均GPA(我想要的),但它们都是相同的。我已经在这个小问题上待了好几个小时,并希望能够继续我的任务,但这给了我太多的麻烦。代码如下:

<T> {
   for $dc in distinct-values(doc("ComS363/UniversityDatasets/Student.xml")/Students/Student/Classification)
   let $student := doc("ComS363/UniversityDatasets/Student.xml")/Students/Student
   let $aveGPA := avg($student/GPA)
   where $student/Classification = $dc
   return
   <Classification>{$aveGPA}</Classification>
} </T>;

我的学生表的设置如下:

<Students>
  <Student>
    <StudentID>118784412</StudentID>
    <Classification>Sophomore</Classification>
    <GPA>3.19</GPA>
    <MentorID>201586985</MentorID>
    <CreditHours>39</CreditHours>
  </Student>
.
.
.
.
</Students>

那么你们有什么想法我为什么没有获得独特的平均GPA分类? 在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您的where子句会过滤返回的结果,而不是前面的变量绑定。因此,avg($student/GPA)将始终评估所有学生的平均GPA。

相反,将过滤步骤与变量绑定结合起来:

let $aveGPA := avg($student[Classification = $dc]/GPA)

为了更好的可读性,您可以将谓词条件应用于$student变量:

let $student := doc("ComS363/UniversityDatasets/Student.xml")/Students/Student[Classification = $dc]
let $aveGPA := avg($student/GPA)
相关问题