从Sql中的XML中提取数据的SUM
我在 SQL 表中有一个像这样的 XML 字段,
<Root>
<Name>Apollo</Name>
<Code>1000</Code>
<Code>2000</Code>
<Code>3000</Code>
</Root>
我需要编写一个 SQL 查询来选择“名称”和“代码”值的总和,
SELECT
T1.c.value('Name[1] AS VARCHAR(100)') AS Name,
T1.c.value('Code[1] AS NUMERIC(10,5)') AS TotalCode
FROM TableName
CROSS APPLY xmlField.nodes('Root') AS T1(c)
它给我的输出如下所示:
Name Code
---------------------------
Apollo 1000
Apollo 2000
Apollo 3000
但我需要所有代码标签的值的总和,如下所示:
Name Code
---------------------------
Apollo 6000
有什么想法如何获得标签值的总和吗?
I have an XML field in SQL table like this
<Root>
<Name>Apollo</Name>
<Code>1000</Code>
<Code>2000</Code>
<Code>3000</Code>
</Root>
I need to write an SQL query to select the 'Name' and SUM of 'Code' values
SELECT
T1.c.value('Name[1] AS VARCHAR(100)') AS Name,
T1.c.value('Code[1] AS NUMERIC(10,5)') AS TotalCode
FROM TableName
CROSS APPLY xmlField.nodes('Root') AS T1(c)
it gives me output like this:
Name Code
---------------------------
Apollo 1000
Apollo 2000
Apollo 3000
But I need SUM of values of all the Code tags like this:
Name Code
---------------------------
Apollo 6000
Any ideas how to get sum of tag values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是最“优雅”的,我确信有一个更直接的路线,但你可以尝试这个
基本上,这首先从 XML 字段项中提取数据,然后按名称分组并给出总和。就像我说的,不优雅但有效!
This isn't the most "elegant" and I'm sure there is a more direct route, but you can try this
Basically this first pulls the data out of the XML field items and then groups by Name and gives the sum. Like I said, not elegant but works!
您可以使用此 XQuery:
示例数据:
输出:
You can use this XQuery:
Sample data:
Output: