Robert019
Robert019

Reputation: 53

Count in xquery

I'm trying to solve this question but this code give me the result without counting it. What i mean it's that i need it to be a 13 but the result its divided by rows with a value of 1.

1

1

1

1

1

1

1

1

1

1

1

1

1

This is the question and this is what i have done.

List the number of countries that have a border (element ) in a country that has a Buddhist religion (element , value "Buddhist"). The correct query has to return the value 13.

for $var in /mondial/country
let $religion:=/mondial/country[religions="Buddhist"]/data(@id)
where $var /border/@country=$religion
return data (count($var/name) 

Upvotes: 1

Views: 61

Answers (2)

Mads Hansen
Mads Hansen

Reputation: 66781

Rather than returning the count for each item as you iterate, return each selected item and assign it to a variable, then you can get a count of the items of the sequence assigned to that variable:

let $names := 
  for $var in /mondial/country
  let $religion:= /mondial/country[religions="Buddhist"]/data(@id)
  where $var/border/@country=$religion
  return $var/name 
return count($names)

You could also do this in a single XPath statement: count(/mondial/country[border/@country=/mondial/country[religions="Buddhist"]/data(@id)])

Upvotes: 0

Jack Fleeting
Jack Fleeting

Reputation: 24930

This should get you there. I changed variable names to make things a bit more readable:

let $country := mondial/country
let $buddhist := $country[religions[./text()="Buddhist"]]/@id
return  count($country[.//border[@country=$buddhist]])

Output:

13

Upvotes: 1

Related Questions