简体   繁体   English

四舍五入后的Xquery SUM

[英]Xquery SUM after value has been rounded

I want to sum the quantity of all products/Product/Quantity after the value has been rounded. 我想对值四舍五入后的所有产品/产品/数量的数量求和。

My XML looks like: 我的XML看起来像:

<Products>
  <Product>
    <ExternalId>116511</ExternalId>
    <Price>2.99 </Price>
    <Quantity>1.500 </Quantity>
    <NetValue>4.08 </NetValue>
  </Product>
  <Product>
    <ExternalId>116510</ExternalId>
    <Price>2.99 </Price>
    <Quantity>1.500 </Quantity>
    <NetValue>4.08 </NetValue>
  </Product>
  <Product>
    <ExternalId>116512</ExternalId>
    <Price>1.99 </Price>
    <Quantity>10.000 </Quantity>
    <NetValue>18.09 </NetValue>
  </Product>
  <Product>
    <ExternalId>329245</ExternalId>
    <Price>59.99 </Price>
    <Quantity>1.000 </Quantity>
    <NetValue>54.53 </NetValue>
  </Product>
</Products> 

The above XML is stored in x with column of Data. 上面的XML与Data列一起存储在x中。

I've tried using xQuery sum and round functions like so but this only rounds and sums the first instance of Quantity (ie sum(round(1.5)) = 2) : 我已经尝试过使用xQuery sum和round这样的函数,但是这只会对数量的第一个实例进行舍入和求和(即sum(round(1.5())= 2)):

SELECT Data.Value('(Products/Product/ExternalId/text()[1]', 'float') AS ExternalId,
x.Data.value('sum(round((/row/Products[1]/Product/Quantity)[1]))', 'float') Trn_Quantity
FROM x

You can try using XQuery for loop construct to round individual Quantity and pass them to sum() , something like this : 您可以尝试使用XQuery for循环结构舍入单个Quantity并将其传递给sum() ,如下所示:

SELECT 
    Data.Value('(Products/Product/ExternalId/text()[1]) AS ExternalId,
    x.Data.value('
        sum(
            for $quantity in /Products[1]/Product/Quantity
            return round($quantity)
        )
    ', 'float') Trn_Quantity
FROM x

Quick test here : http://sqlfiddle.com/#!3/9eecb7/7351 在这里快速测试: http : //sqlfiddle.com/#!3/9eecb7/7351

You could use CROSS APPLY to get all quantity nodes, then just sum them up in regular SQL; 您可以使用CROSS APPLY来获取所有数量的节点,然后将其汇总为常规SQL;

SELECT SUM(ROUND(p.value('.', 'float'), 0)) AS Quantity
FROM mytable x
CROSS APPLY data.nodes('/Products/Product/Quantity') t(p)

...or, to sum other product fields too, get the product nodes with cross apply and sum the sub-nodes by name; ...或者,也可以对其他产品字段求和,获得具有交叉应用的产品节点并按名称对子节点求和;

SELECT SUM(p.value('(./Price)[1]', 'float')) AS Price,
       SUM(ROUND(p.value('(./Quantity)[1]', 'float'), 0)) AS Quantity
FROM mytable x
CROSS APPLY data.nodes('/Products/Product') t(p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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