Sql 值四舍五入后的Xquery求和

Sql 值四舍五入后的Xquery求和,sql,sql-server,xquery,xquery-sql,Sql,Sql Server,Xquery,Xquery Sql,我想对数值四舍五入后所有产品/产品/数量的数量求和 我的XML看起来像: <Products> <Product> <ExternalId>116511</ExternalId> <Price>2.99 </Price> <Quantity>1.500 </Quantity> <NetValue>4.08 </NetValue> <

我想对数值四舍五入后所有产品/产品/数量的数量求和

我的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> 

您可以尝试使用XQuery
for
循环构造对单个
数量进行四舍五入,并将其传递给
总和()
,如下所示:

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
这里的快速测试:

您可以使用它来获取所有的quantity节点,然后在常规SQL中求和它们

SELECT SUM(ROUND(p.value('.', 'float'), 0)) AS Quantity
FROM mytable x
CROSS APPLY data.nodes('/Products/Product/Quantity') t(p)
…或者,若要对其他产品字段求和,请使用交叉应用获取产品节点,并按名称对子节点求和

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)

不确定我是否理解您的查询试图做什么。你想要第一个外显值和所有数量的总和吗?谢谢har07,这很好用。不知道可以在xQuery中使用循环。你每天都会学到新东西。
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)