我有一個很大的XML文件,其中包含有關酒店連鎖店的數據。每週,每天,每家酒店他們都會保留一些數據以供他們的報告:計算平均值的平均值
<Report week="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="report.xsd">
<Days>
<Day id="1" naam="Monday">
<Hotels>
<Hotel id="1" naam="Bonotel Antwerp">
<Stays>
<Stay id="1">
<Room id="1" number="1"/>
<Roomtype id="1" naam="oneperson" price="20.00"/>
<Period id="1" naam="lowseason" price="20.00"/>
<Formula id="1" naam="roomandbreakfast" price="20.00"/>
<Facilities>
<Facility id="1" naam="swimming" price="5.00"/>
<Facility id="2" naam="golf" price="20.00"/>
</Facilities>
<Guest id="1" naam="John Williams"/>
</Stay>
<Stay id="2">
<Room id="2" number="2"/>
<Roomtype id="1" naam="oneperson" price="20.00"/>
<Period id="1" naam="lowseason" price="20.00"/>
<Formula id="1" naam="roomandbreakfast" price="20.00"/>
<Facilities>
<Facility id="2" naam="golf" price="20.00"/>
<Facility id="3" naam="minibar" price="10.00"/>
</Facilities>
<Guest id="2" naam="Ray Kurzweil"/>
</Stay>
<Stay id="3">
<Room id="3" number="3"/>
<Roomtype id="2" naam="twoperson" price="40.00"/>
<Period id="1" naam="lowseason" price="20.00"/>
<Formula id="2" naam="halfpension" price="30.00"/>
<Facilities>
<Facility id="4" naam="tennis" price="20.00"/>
<Facility id="4" naam="tennis" price="20.00"/>
</Facilities>
<Guest id="3" naam="Stephen Hawking"/>
</Stay>
</Stays>
</Hotel>
(: ... Other Hotels ... :)
</Hotels>
</Day>
(: ... Other Days ... :)
</Days>
</Report>
使用XQuery,我必須計算平均客人花費的費用。這是Roomtype價格,Periode價格,公式價格和設施總和的總和。我想出了這個XQuery的:
xquery version "1.0";
<ReportResult week="1">
{
for $x in (1 to 7)
return
for $stays in doc("report.xml")//Report/Days/Day[@id=$x]/Hotels/Hotel[@id=1]/Stays
let $average := avg(
for $v in $stays/Stay
return sum($v/Roomtype/@price) + sum($v/Facilities/Facility/@prijs) + sum($v/Formula/@price) + sum($v/Period/@price)
)
return
<AverageSpending hotel="Bonotel Antwerpen" day="{data($x)}">
{data(round-half-to-even($average, 2))}
</AverageSpending>
}
</Reportresult>
這將產生的結果我想到:
<Reportresult week="1">
<Averagespending hotel="Bonotel Antwerpen" day="1">101.67</AverageSpending>
<Averagespending hotel="Bonotel Antwerpen" day="2">321.67</AverageSpending>
(: ... etc... :)
<Averagespending hotel="Bonotel Antwerpen" day="2">255</AverageSpending>
</Reportresult>
不過,我還想來計算總的平均水平。所以所有的平均值除以7天的總和來輸出類似的東西
<TotalAverage>198,67</TotalAverage>
但是我在計算這個總平均時遇到了麻煩。在Java中,我會使用一個總變量並將其與每個循環的計算平均值相加,但顯然這在這裏不起作用。我如何能夠用XQuery做到這一點?謝謝。
請給我們一些示例數據一起工作和/或提供一些不需要數據的抽象例子。 – 2012-08-13 11:35:37
完成。請參閱編輯。 – Matthias 2012-08-13 12:06:38