我希望在价值四舍五入后计算所有产品/产品/数量的数量。
我的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>
上述XML存储在x中,其中包含Data。
列我尝试过像这样使用xQuery求和和舍入函数,但这只是舍入并汇总了Quantity的第一个实例(即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
答案 0 :(得分:2)
您可以尝试使用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
答案 1 :(得分:1)
您可以使用CROSS APPLY
获取所有数量的节点,然后在常规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)