sum some xml nodes values in sql server 2008

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-19 08:55:27

问题


Please consider this XML:

<Parent ID="p">
    <Child ID="1">10</Child > 
    <Child ID="2">20</Child > 
    <Child ID="3">0</Child > 
</Parent > 

I want to SUM all child value inside the Parent node with ID="p".for above example I want query return 30

How I can do this?


回答1:


select @xml.value('sum(/Parent[@ID = "p"]/Child)', 'float') as Sum

The use of float protects against there being no Parent with that ID. You can then cast this result to int.




回答2:


Try this :-

 Declare @xml xml 
set @xml='<Parent ID="p">
         <Child ID="1">10</Child > 
         <Child ID="2">20</Child > 
         <Child ID="3">0</Child > 
          </Parent >'

 Select @xml.value('sum(/Parent/Child)','int') as Sum

Result : 30

or if you want the sum for a specific Parent ID then try the below query

 Select @xml.value('sum(/Parent/Child)','int') AS SumVal
 where @xml.exist('/Parent[@ID="p"]') = 1;

Demo in SQL FIDDLE




回答3:


Try this one -

DECLARE @XML XML
SELECT @XML = '
<Parent ID="p">
    <Child ID="1">10</Child > 
    <Child ID="2">20</Child > 
    <Child ID="3">0</Child > 
</Parent >
<Parent ID="p2">
    <Child ID="1">15</Child > 
    <Child ID="2">20</Child > 
    <Child ID="3">5</Child > 
</Parent >'

SELECT 
      value = SUM(t.value)
    , t.id 
FROM (
    SELECT 
          value = p.value('.', 'INT')
        , id = p.value('./../@ID', 'VARCHAR(50)')
    FROM @XML.nodes('/Parent/Child') t(p)
) t
--WHERE t.id = 'p'
GROUP BY t.id



回答4:


Try this :

DECLARE @SearchKeyWords XML 

SET @SearchKeyWords =
'<Parent ID=''p''>
    <Child ID="1">10</Child > 
    <Child ID="2">20</Child > 
    <Child ID="3">0</Child > 
</Parent >' 

DECLARE @TempSearchKeyWords TABLE
        (
            SearchKeyWord INT
        )

INSERT INTO @TempSearchKeyWords                     
SELECT SearchKeyWords.SearchKeyword.value('.',' int ') AS SearchKeyword             
FROM @SearchKeyWords.nodes('/Parent/Child') AS SearchKeyWords(SearchKeyword)

SELECT SUM(SearchKeyWord) FROM @TempSearchKeyWords

This will return 30.



来源:https://stackoverflow.com/questions/16144494/sum-some-xml-nodes-values-in-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!