2

我有一个 SQL 查询:

SELECT ShipVia, SUM(Freight)
FROM Orders
GROUP BY ShipVia

它从访问数据库返回以下值

Ship Via  TotalFreight
   1       $16,185.33
   2       $28,244.85
   3       $20,512.51

我正在尝试将其转换为 xquery(使用 xquery 1.0)

到目前为止,我有这个,

xquery version "1.0";
for $x in doc("Orders.xml")/dataroot/Orders
return
<OrderDetails>
{
    $x/ShipVia,
    <TotalFreight>{sum($x/Freight)}</TotalFreight>
}
</OrderDetails>

但是,这会像我一样输出每个订单以及运费

SELECT ShipVia, Freight
FROM Orders

在 SQL 中

如何使 xquery 像 SQL 命令一样实际添加每一个

例如,这些是 Orders.xml 文件中的三个订单

<dataroot>
    <Orders>
        <ShipVia>1</ShipVia>
        <Freight>32.38</Freight>
    </Orders>
    <Orders>
        <ShipVia>1</ShipVia>
        <Freight>11.61</Freight>
    </Orders>
    <Orders>
        <ShipVia>2</ShipVia>
        <Freight>65.83</Freight>
    </Orders>
</dataroot>

编辑:剥离不必要的节点(添加重复)

4

1 回答 1

2

以下是在 XQuery 1.0(缺少 XQuery 3.0 的本机group by运算符)中执行此操作的一种方法:

let $doc := 
    <dataroot>
        <Orders>
            <ShipVia>1</ShipVia>
            <Freight>32.38</Freight>
        </Orders>
        <Orders>
            <ShipVia>1</ShipVia>
            <Freight>11.61</Freight>
        </Orders>
        <Orders>
            <ShipVia>2</ShipVia>
            <Freight>65.83</Freight>
        </Orders>
    </dataroot>

let $ship_via_values := distinct-values($doc/Orders/ShipVia/text())
for $ship_via_value in $ship_via_values
return
  <OrderDetails>
    <ShipVia>{$ship_via_value}</ShipVia>
    <TotalFreight>{
      sum($doc/Orders[ShipVia=$ship_via_value]/Freight)
    }</TotalFreight>
  </OrderDetails>

此查询返回以下结果:

<OrderDetails>
  <ShipVia>1</ShipVia>
  <TotalFreight>43.99</TotalFreight>
</OrderDetails>
<OrderDetails>
  <ShipVia>2</ShipVia>
  <TotalFreight>65.83</TotalFreight>
</OrderDetails>

...这似乎是所需的输出。

于 2012-03-13T00:32:03.643 回答