【问题标题】:How can I add in a for loop in Xquery?如何在 Xquery 中添加 for 循环?
【发布时间】:2017-05-04 14:09:33
【问题描述】:

我在 Xquery 中的一个练习有问题。

这是练习:

如果他的课程的所有地点都已完成,那么获取以 Michael 开头的每位教师每月将获得的收益(所有教师的总和)。

这是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”,但这不允许我将位置乘以价格,我不知道为什么。有人可以帮我吗?非常感谢。

【问题讨论】:

标签: xquery


【解决方案1】:

您的$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 前身支持 XQuery 3.0,您可以使用映射 ! 运算符并编写:

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

【讨论】:

    猜你喜欢
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2020-07-09
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多