SUM函数XQUERY

时间:2014-04-09 18:35:42

标签: xml function xpath sum xquery

我正在使用XQUERY执行添加:以下是保存在数据库中的XML结构:

<?xml version="1.0" encoding="UTF-8"?>
<shop>
<products>
    <product cod="P0002">
        <name>Windows 8</name>
        <price unit="Euros">120</price>
    </product>
    <product cod="P0008">
        <name>Pendrive 32GB</name>
        <price unit="Euros">16</price>
    </product>
    <product cod="P0004">
        <name>Laptop ASUS</name>
        <price unit="Euros">400</price>
    </product>
    <product cod="P1600">
        <name>Laptop Mouse</name>
        <price unit="Euros">10</price>
    </product>
    <product cod="P3000">
        <name>Microsoft Office 2013</name>
        <price unit="Euros">119</price>
    </product>        
    <product cod="P5000">
        <name>Hard Disk 1 TB</name>
        <price unit="Euros">78</price>
    </product>
</products>   
<shoppings>
    <amount product="P0004">5</amount>
    <amount product="P0002">3</amount>
    <amount product="P0004">7</amount>
    <amount product="P1600">2</amount>
    <amount product="P0004">1</amount>
    <amount product="P0008">3</amount>
</shoppings>

我需要显示每个产品的名称和销售的单位总数(如果没有销售,则显示0)。我需要这个结果,但我尝试并尝试但没有成功:

<product>
   <name>Windows 8</name>
   <amount>3</amount>
</product>
<product>
   <name>Pendrive 32GB</name>
   <amount>3</amount>
</product>
<product>
   <name>Laptop ASUS</name>
   <amount>13</amount>
</product>
<product>
   <name>Laptop Mouse</name>
   <amount>2</amount>
</product>
<product>
   <name>Microsoft Office 2013</name>
   <amount>0</amount>
</product>
<product>
   <name>HArd Disk 1 TB</name>
   <amount>0</amount>
</product>

2 个答案:

答案 0 :(得分:0)

如果你分享了一些尝试,那就太好了。这个提示足够好了吗?

let $amount := sum(distinct-values($node//shoppings/amount[@product ='P0004']))

答案 1 :(得分:0)

for $p in //product return
<product ...>
  <amount>{sum(//amount[@product=$p/@cod])}</amount>
</product>
相关问题