1

我有一个如下所示的 xml 文件,我想对 toyID 进行分组并获得该玩具已售出的总和。并按销售额最高的 toyID 排序。但是我编写的代码能够汇总玩具销售量,但是按玩具销售量最高的顺序不起作用。我能知道我做错了哪一部分吗?

 ToySale.XML
 <toySale companyID="1" toyID="11" >
   <amount>15</amount>
 </toySale>
 <toySale companyID="3" toyID="11" >
   <amount>12</amount>
 </toySale>
 <toySale companyID="1" toyID="22" >
   <amount>3</amount>
 </toySale>
 <toySale companyID="2" toyID="33" >
   <amount>7</amount>
 </toySale>

下面是我写的代码:

for $t in distinct-values(ToySale.xml")//@toyID)
return <toyID>
            toyID : {$t} 

          <totalSale>{sum(for $sum in (ToySale.xml")//toySale
                     order by $sum/@toyID/../amount     
                     where $t=$sum/@toyID
                     return $sum/@productID/../amount)  }

           </totalSale

        </toyID>
4

2 回答 2

0
(:
     Find total sales of each toy sold!

     I tried this query here!   http://www.zorba-xquery.com/html/demo
 :)
let $xml := (
    <toySales>
        <toySale companyID="1" toyID="11" >
            <amount>15</amount>
        </toySale>
        <toySale companyID="3" toyID="11" >
            <amount>12</amount>
        </toySale>
        <toySale companyID="1" toyID="22" >
            <amount>3</amount>
        </toySale>
        <toySale companyID="2" toyID="33" >
            <amount>7</amount>
        </toySale>
    </toySales>
)

let $toy-sales := $xml//toySale
for $toy-id in distinct-values($xml//@toyID)
let $total-amount-sold := fn:sum($toy-sales[@toyID = $toy-id]/amount)
return (

   element toy-sale {       
        attribute toy-id { $toy-id },
        text { 
            fn:concat("Total amount sold: ", $total-amount-sold)        
        }
   }
)

返回

<toy-sale toy-id="11">Total amount sold: 27</toy-sale>
<toy-sale toy-id="22">Total amount sold: 3</toy-sale>
<toy-sale toy-id="33">Total amount sold: 7</toy-sale>

xquery #1 最好的^^

于 2012-10-06T07:42:12.383 回答
0

这个查询

   for $vId
     in (/*/toySale/@toyID)
                     [index-of(/*/toySale/@toyID, .)[1]]

    let $vSales := /*/toySale[@toyID eq $vId]

    order by sum($vSales/amount) descending

   return
     <sale toy-id="{$vId}" total="{sum($vSales/amount)}"/>

应用于提供的 XML 文档时

<toySales>
    <toySale companyID="1" toyID="11" >
        <amount>15</amount>
    </toySale>
    <toySale companyID="3" toyID="11" >
        <amount>12</amount>
    </toySale>
    <toySale companyID="1" toyID="22" >
        <amount>3</amount>
    </toySale>
    <toySale companyID="2" toyID="33" >
        <amount>7</amount>
    </toySale>
</toySales>

产生想要的正确结果

<sale total="27" toy-id="11"/>
<sale total="7" toy-id="33"/>
<sale total="3" toy-id="22"/>

等效且稍短的查询

   for $vId in distinct-values(/*/toySale/@toyID)

     let $vSales := /*/toySale[@toyID eq $vId]

     order by sum($vSales/amount) descending

    return
       <sale toy-id="{$vId}" total="{sum($vSales/amount)}"/>
于 2012-10-06T17:15:42.670 回答