简体   繁体   中英

XQuery - Sum attributes for all element which have another specific attribute value

I need to add balance for each prod "type" such that what remains is one element with the total balance for the prod "type"

This is what I have

let $input := <products>
                <prod balance="20000" code="car"/>
                <prod balance="50000" code="house"/>
                <prod balance="50000" code="car"/>
              </products>         
       let $sum_val_car :=  sum($input//prod/@balance )
       let $count_val_car := count($input//prod[@code='car'])
       let $sum_val_house :=  sum($input//prod/@balance)
       let $count_val_house := count($input//prod[@code='house'])
       
       
  return  <products>
            <prod count="{$count_val_car}" balance="{$sum_val_car}" code="car"/>
            <prod count="{$count_val_house}" balance="{$sum_val_house}" code="house"/>
         </products>

I need to modify $sum_val_car and $sum_val_house somehow to only sum the elements with the code attribute eqaul to the repective value. Is there a way to do this?

$input//prod[@code='house']/@balance

This chooses balance from prod elements with code ='house'

Solution is then

let $sum_val_house :=  sum($input//prod[@code='house']/@balance)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM