xquery中的SUM和GROUP BY与1 xml文件

时间:2012-03-12 23:21:01

标签: xml xquery xmlspy

我有一个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命令添加每个xquery

这些是来自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>

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

1 个答案:

答案 0 :(得分: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>

......似乎是理想的输出。