Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting SUM of data from XML in Sql

Tags:

sql

xml

field

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?

like image 665
Arpit Khandelwal Avatar asked Jul 22 '11 07:07

Arpit Khandelwal


People also ask

How do I get data from XML format in SQL Server?

SQL Server lets you retrieve data as XML by supporting the FOR XML clause, which can be included as part of your query. You can use the FOR XML clause in the main (outer) query as well as in subqueries. The clause supports numerous options that let you define the format of the XML data.

How do you find the sum of records in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.

How can I get SQL query results in XML?

You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.


1 Answers

This isn't the most "elegant" 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 out of the XML field items and then groups by Name and gives the sum. Like I said, not elegant but works!

like image 97
Mitchel Sellers Avatar answered Oct 11 '22 17:10

Mitchel Sellers