Reputation: 821
I have an sql query. I need to sum two xml nodes with the same names () but different attributes (ident= "1cat" + "3cat"). I can get nodes by their number ([1] and [3]) but I need to sum them by "ident". How can I sum 1Category and 3Category by their idents?
DECLARE @xml XML
SET @xml =
'<cat:catalog xmlns:cat="http://datypic.com/cat" xmlns:prod="http://datypic.com/prod">
<cat:number ident="1Category">10</cat:number>
<cat:number ident="2Category">20</cat:number>
<cat:number ident="3Category">30</cat:number>
</cat:catalog>';
WITH XMLNAMESPACES (
'http://datypic.com/cat' AS cat
)
SELECT
c.c.value('(cat:number/text())[1]', 'INT') '1Category',
c.c.value('(cat:number/text())[3]', 'INT') '3Category'
FROM @xml.nodes('cat:catalog') c(c)
Upvotes: 0
Views: 184
Reputation: 138960
WITH XMLNAMESPACES (
'http://datypic.com/cat' AS cat
)
SELECT @xml.value('sum(/cat:catalog/cat:number[@ident=("1Category", "3Category")]/text())', 'INT')
Upvotes: 1
Reputation: 51494
WITH XMLNAMESPACES (
'http://datypic.com/cat' AS cat
)
SELECT
c.c.value('(cat:number[@ident="1Category"])[1]', 'INT') +
c.c.value('(cat:number[@ident="3Category"])[1]', 'INT')
FROM @xml.nodes('cat:catalog') c(c)
Upvotes: 1