2017-05-04 204 views
1

我在Xquery中有一個練習題。如何在Xquery中添加for循環?

這是鍛鍊:

得到的每一位老師將每月獲得其名稱與邁克爾·如果開始他的課程所有的地方都完成(所有的總和)。

這是XML文件:

<shop> 
<training> 
    <course id="1"> 
     <name>Java</name> 
     <price fee="Monthly">27</price> 
     <places>20</places> 
     <teacher>Michael James</teacher> 
    </course> 
    <course id="2"> 
     <name>Android</name> 
     <price fee="Monthly">47</price> 
     <places>15</places> 
     <teacher>Michael Pit</teacher> 
    </course> 
    <course id="3"> 
     <name>SEO</name> 
     <price fee="Monthly">37</price> 
     <places>55</places> 
     <teacher>Michael Smith</teacher> 
    </course> 
    <course id="4"> 
     <name>HTML</name> 
     <price fee="Monthly">99</price> 
     <places>10</places> 
     <teacher>Michael Kit</teacher> 
    </course> 
    <course id="5"> 
     <name>CSS</name> 
     <price fee="Monthly">749</price> 
     <places>5</places> 
     <teacher>George Pet</teacher> 
    </course> 

我試圖做到這一點:

` for $x in doc("LM")//course[starts-with(teacher, "Michael")] 
let $monthly-profits-by-course := $y/places * $y/price 
let $total-profits := sum($monthly-profits-by-course) 
return 
<courses> 
    <michael_profits>{$total-profits}</michael_profits> 
</courses>` 

這是結果:

<courses> 
<michael_profits>540</michael_profits> 
</courses> 
<courses> 
<michael_profits>705</michael_profits> 
</courses> 
<courses> 
<michael_profits>2035</michael_profits> 
</courses> 
<courses> 
<michael_profits>990</michael_profits> 
</courses> 

它名單當然是每月的利潤,但我需要總利潤,我不知道我該怎麼做。我已經嘗試過只用「let」而不是「for」,但這不能讓我按價格乘以地點,我不知道爲什麼。有人可以幫我嗎?非常感謝你。

+0

請包括您已經嘗試過的代碼。另外,請遵循http://stackoverflow.com/help/how-to-ask中的其他建議。 – BPS

回答

2

您的$monthly-profits-by-course將始終是單個值,而不是您在每個課程中迭代的順序。因此,sum($monthly-profits-by-course)將等於$monthly-profits-by-course本身。你需要的是每個老師返回的利潤序列像你已經做了:

for $x in doc("LM")//course[starts-with(teacher, "Michael")] 
return $y/places * $y/price 

,然後計算所有這些值的總和。相結合,這看起來像:

let $all-sums := 
    for $x in doc("LM")//course[starts-with(teacher, "Michael")] 
    return $y/places * $y/price 
return sum($all-sums) 

而且可以縮短這個簡單到:

sum(
    for $x in doc("LM")//course[starts-with(teacher, "Michael")] 
    return $y/places * $y/price 
) 

如果您的XQuery precessor支持的XQuery 3.0,你可以使用地圖!操作和寫:

sum(doc("LM")//course[starts-with(teacher, "Michael")] ! (./places * ./price)) 
+0

它工作完美。謝謝dirkk! – user7753413