Summing Xml Data (concisely?)

  • I have an xml column in table MyTable called xData_1.

    Please see attached xml text file for the data contained in the table. It's simple stuff.

    I want to look at some specific xml within each row and sum it to a single value.

    I've tried a lot of things but I'm not getting any closer. Anyone have any ideas? Thanks!

    -- query -- data is in attachment

    select xData_1.query('

    for $x in /items/item

    where $x/@year=2009 and $x/@month=6

    return sum($x/@amount)

    ') from MyTable

    -- MyTable schema

    CREATE TABLE MyTable (xData_1 xml)

  • Maybe this

    select xData_1.value('

    sum(for $x in /items/item

    where $x/@year=2009 and $x/@month=6

    return $x/@amount)','int')

    from MyTable

    ____________________________________________________

    Deja View - The strange feeling that somewhere, sometime you've optimised this query before

    How to get the best help on a forum

    http://www.sqlservercentral.com/articles/Best+Practices/61537
  • Thanks Mark! That didn't quite get all the way there because it still returned 12 rows but it DID give me the push I needed to crack it. 😀

    select sum(xData_1.value('

    sum(for $x in /items/item

    where $x/@year=2009 and $x/@month=6

    return $x/@amount)','float'))

    from MyTable

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply