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?
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With