“NaN” stands for “Not a Number” and is what you get when you try to do arithmetic with non-numeric data, which is what you have done here.

Let’s translate your query into English:

`sum(//Publikation[EinrichtungID='0104005' and Jahr='2005' and Bewertung/@HsFb='0104'])`

The “sum” function takes a sequence of numbers and returns their sum, so the first thing we have to do is evaluate its argument:

`//Publikation[EinrichtungID='0104005' and Jahr='2005' and Bewertung/@HsFb='0104']`

This is a path expression. The first part, “//Publikation” says to search the documents in your collection for all “Publikation” elements at whatever level of nesting they occur. The next part, in brackets, is a filter that will remove all nodes in the result set that don’t meet the criteria; in this case it will exclude any “Publikation” elements whose “EinrichtungID” child isn’t ‘0104005’ or whose “Jahr” child isn’t ‘2005’ or whose “Bewertung” child doesn’t have a “HsFb” attribute of ‘0104’. But the point to note here is that the result of this expression is a sequence of “Publikation” nodes which the “sum” function must try to convert to numbers. But in fact the “Publikation” nodes have a complex type and can’t be converted to numbers, so the “sum” function returns ‘NaN’.

Now let’s look at the argument to “sum” in your query that works:

`/Publikation/Bewertung[@HsFb="0104"]`

This expression in English means “find all the ‘Bewertung’ nodes that are children of ‘Publikation’ documents, and then filter out all except the ones that have a ‘HsFb’ attribute of ‘0104’.” The crucial difference is that this expression returns a sequence of “Bewertung” elements, and these elements have simple content that can be interpreted as a number.

So how should we code what I think is what you wanted in the query that didn’t work? Let’s try this as the argument to “sum”:

`/Publikation[EinrichtungID='0104005'][Jahr='2005]/Bewertung[@HsFb='0104']`

This expression says “select all the ‘Publikation’ documents and filter out all except those that have an ‘EinrichtungID’ child of ‘0104005’, and then filter out those that don’t have a ‘Jahr’ child of ‘2005’. Using this sequence of documents as a starting point, create a new sequence of all their ‘Bewertung’ children, and then filter out the ones that don’t have a ‘HsFb’ attribute of ‘0104’.” The result is a sequence of “Bewertung” elements, which can be converted to numbers and summed.