2012-11-15 43 views
0

我試圖讓下面的MySQL查詢的相當於一個XQueryMySQL查詢的XQuery

SELECT S.Classification, COUNT(S.Classification) AS "No. Students", AVG(S.GPA) AS "AVG 
    Class. GPA" 
FROM Student S 
GROUP BY S.Classification 
ORDER BY S.Classification ASC; 

此輸出: http://i.stack.imgur.com/Iu0d4.png

如果我的數據庫看起來像:

CREATE TABLE 'Student' (
'StudentID' CHAR(9) NOT NULL, 
'Classification' CHAR(10) NULL DEFAULT NULL, 
'GPA` DOUBLE NULL DEFAULT NULL, 
'MentorID' CHAR(9) NULL DEFAULT NULL, 
'CreditHours' INT(11) NULL DEFAULT NULL, 
PRIMARY KEY ('StudentID') 
) 

而且在XML中:

<Document> 
    <Table> 
    <StudentID>118784412</StudentID> 
    <Classification>Sophomore</Classification> 
    <GPA>3.19</GPA> 
    <MentorID>201586985</MentorID> 
    <CreditHours>39</CreditHours> 
    </Table> 
</Document> 

我不知道如何在xquery中使用count()和avg()。 我從哪裏開始?任何幫助表示讚賞,謝謝。

+0

什麼是您的XQuery處理器? XQuery 1.0沒有明確支持Group by。它在1.1和3.0版本中,但目前支持這些規範的實現並不多。但是,有特定於實現的擴展和解決方法。如果您可以使用它,XSLT 2也是一個很好的選擇。理想的解決方案將取決於這些變量。 – wst

+0

XQuery 1.0。我知道我不能使用'group by'。 – user884685

+0

您使用的是什麼xQuery處理器?解決方案的最佳組合將是特定於實現的。 – wst

回答

1

您可以使用XQuery 3.0中定義的group by運算符輕鬆實現此目的。假設給定的XML是在變量$doc和數據庫的每行是另一個<Table />節點,你可以做這樣的:

for $student in $doc/Table 
let $classification := $student/Classification 
group by $classification 
order by $classification 
return 
    <output> 
    <Classification>{$classification}</Classification> 
    <NoStudents>{count($student)}</NoStudents> 
    <AvgGPA>{avg($student/GPA)}</AvgGPA> 
    </output> 

有一些(優秀)的XQuery處理器,支持的XQuery 3.0 ,例如BaseXeXistZorba

+0

我不認爲我可以'分組'。我試過並得到一個錯誤,因此我不認爲我能夠使用XQuery 3.0。 – user884685

+0

您使用什麼處理器? – dirkk