2012-10-06 72 views
1

我有一個像下面這樣的xml文件,我想分組玩具ID並獲得玩具銷售量的總和。並以最高銷售額的玩具ID來訂購它。但我寫的代碼能夠對玩具銷售量進行總結,但玩具銷售量最高的訂單無法正常工作。我知道我錯誤地做了哪一部分?無法工作的訂單

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> 

回答

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"/> 

一個等價的和斯萊TLY較短查詢

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)}"/> 
+0

感謝alot.learned新的東西。 dint知道我們可以在order by子句上使用聚合函數。 – setiasetia

+0

@setiasetia,不客氣。 –

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最好的^^

+0

測試,是的,它的工作原理too.thanks很多的幫助 – setiasetia