Extract SUM data from XML to Sql

I have an XML field in an 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 values ​​"Name" and SUM "Code"

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)

he gives me the output as follows:

Name                Code
---------------------------
Apollo              1000
Apollo              2000
Apollo              3000

But I need the SUM values ​​of all Code tags, like this:

Name                Code
---------------------------
Apollo              6000

Any ideas on how to get the sum of the tag values?

+5
source share
3 answers

This is not the most “elegant” one, and I'm sure there is a more direct route, but you can try this.

Select
    B.Name,
    SUM(B.TotalCode)
FROM 
(
    SELECT 
       T1.c.value('Name[1]', 'VARCHAR(100)') AS Name,
       T1.c.value('Code[1]', 'NUMERIC(10,5)') AS TotalCode
    FROM TableName
    CROSS APPLY xmlField.nodes('Root') AS T1(c)
) AS B
GROUP BY Name

Basically, this first pulls the data from the elements of the XML field, and then groups them by name and gives the sum. As I said, it’s not elegant, but it works!

+3
source

You can use this XQuery:

select t.xmlField.value('(//Name)[1]', 'varchar(max)')
    , t.xmlField.value('fn:sum(//Code)', 'int')
from @t t

:

declare @t table(xmlField xml)

insert @t values('<Root>
 <Name>Apollo</Name>
 <Code>1000</Code>
 <Code>2000</Code>
 <Code>3000</Code>
</Root>'), 
('<Root>
 <Name>Apollo1</Name>
 <Code>1000</Code>
 <Code>2000</Code>
</Root>'),
('<Root>
 <Name>Apollo3</Name>
 <Code>1000</Code>
 <Code>2000</Code>
 <Code>13000</Code>
</Root>')

:

----------------------
Apollo     6000
Apollo1    3000
Apollo3    16000
+2
SELECT 
 T1.c.value('Name[1]', 'VARCHAR(100)') AS Name,
 T1.c.value('sum(Code)', 'NUMERIC(10,5)') AS TotalCode
FROM TableName
CROSS APPLY xmlField.nodes('/Root') AS T1(c)
0

All Articles