我的数据库(xml)为以下:
<db>
<productLine>
<product nr="4567">
<name>Shampoo</name>
<category>Care</category>
</product>
<product nr="4568">
<name>Polish</name>
<category>Care</category>
</product>
<product nr="7010">
<name>Radio</name>
<category>Electronic</category>
</product>
<product nr="7012">
<name>Headphones</name>
<category>Electronic</category>
</product>
</productLine>
<stores>
<store storeNr="1">
<range>
<prodInRange>
<nr>4567</nr>
<salesPrice>20</salesPrice>
</prodInRange>
<prodInRange>
<nr>4568</nr>
<salesPrice>40</salesPrice>
</prodInRange>
<prodInRange>
<nr>7010</nr>
<salesPrice>120</salesPrice>
</prodInRange>
</range>
</store>
<store storeNr="2">
<range>
<prodInRange>
<nr>4567</nr>
<salesPrice>25</salesPrice>
</prodInRange>
<prodInRange>
<nr>7010</nr>
<salesPrice>140</salesPrice>
</prodInRange>
<prodInRange>
<nr>7012</nr>
<salesPrice>50</salesPrice>
</prodInRange>
</range>
</store>
</stores>
</db>
我想显示按CATEGORY分组的产品的平均价格:
想要的输出:
<category value="Care">28.3333</category>
<category value="Electronic">103.3333</category>
处理:平均(20,25,40)和平均(120,140,50)
我已经有以下内容:
let $db := doc("avgCategory.xml")/db
for $pro in $db/productLine/product
let $cat := $pro/category
group by $cat
return
<category val="{$cat}"></category>
但是我不知道如何输出产品类别的平均价格。
正如在新删除的答案中已经指出的那样,在group by
子句之后,$pro
保留了您的组,因此使用<category val="{$cat}">{avg($db/stores/store/range/prodInRange[nr = $pro/@nr]/salesPrice)}</category>
应该计算组中所有产品的平均salesPrice。