0

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)
JohnyMotorhead
  • 675
  • 1
  • 9
  • 18

2 Answers2

1
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) 
podiluska
  • 50,950
  • 7
  • 98
  • 104
1
WITH XMLNAMESPACES ( 
'http://datypic.com/cat' AS cat 
) 
SELECT @xml.value('sum(/cat:catalog/cat:number[@ident=("1Category", "3Category")]/text())', 'INT')
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281