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)

2 Answers 2

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

yes man!! You're saving me 2nd time. that's what I was needed!! thank a lot!!
1
WITH XMLNAMESPACES ( 
'http://datypic.com/cat' AS cat 
) 
SELECT @xml.value('sum(/cat:catalog/cat:number[@ident=("1Category", "3Category")]/text())', 'INT')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.