如何在XQuery中获取节点值的总和?

问题描述 投票:0回答:1

在下面的xml中,有两类与零件和订单相关的信息。 XML:

<mo>
        <parts>
        <part pno="10506">          
            <pname>Land Before Time I</pname>
            <qoh>200</qoh>
            <price>319.99</price>
            <level>20</level>
        </part>
        <part pno="10000">          
            <pname>Bottle</pname>
            <qoh>2</qoh>
            <price>3.00</price>
            <level>2</level>
        </part>
        <part pno="10508">          
            <pname>Land Before Time 3</pname>
            <qoh>202</qoh>
            <price>2.00</price>
            <level>22</level>
        </part>
        <part pno="10509">          
            <pname>Cycle</pname>
            <qoh>202</qoh>
            <price>1.00</price>
            <level>22</level>
        </part>
    </parts>
    <orders>    
        <order ono="1000" >
            <receivedDate>1967-08-17</receivedDate>
            <shippedDate>1967-08-13</shippedDate>
            <items>
                <item>
                    <partNumber>10508</partNumber>
                    <quantity>2</quantity>
                </item>
            </items>
        </order>
        <order ono="1001" >
            <receivedDate>1968-08-14</receivedDate>
            <shippedDate>1968-08-11</shippedDate>
            <items>
                <item>
                    <partNumber>10000</partNumber>
                    <quantity>2</quantity>
                </item>

            </items>
        </order>

        <order ono="1022">
            <receivedDate>1995-02-14</receivedDate>
            <shippedDate>1995-02-13</shippedDate>
            <items>
                <item>
                    <partNumber>10000</partNumber>
                    <quantity>1</quantity>
                </item>
                <item>
                    <partNumber>10508</partNumber>
                    <quantity>2</quantity>
                </item>
                <item>
                    <partNumber>10509</partNumber>
                    <quantity>3</quantity>
                </item>
            </items>
        </order>

    </orders>
</mo>

需求:我想通过XQuery获取订单1022的产品总价。我在下面编写了 xquery 来获取订单号 1022 中零件的价格总和。

X查询:

for
$o in /mo/orders/order,
$p in /mo/parts/part
where
data($o/@ono) = ("1022")
and
data($p/@pno) = $o/items/item/partNumber
return fn:sum($p/price)

但是,此查询返回零件价格,但不返回总价格。 其结果是: 3 2 1

有人知道如何获得价格总和吗?

xml xquery
1个回答
7
投票

您正在总结个人价值观。将

fn:sum()
包裹在查询中,计算每件商品的单独价格。

fn:sum(
  for $item in /mo/orders/order[@ono='1022']/items/item
  return /mo/parts/part[@pno = $item/partNumber]/price * $item/quantity
)
© www.soinside.com 2019 - 2024. All rights reserved.