Question

Return the number of cycles:

let $bd := doc("document")
return count (  for $c in $bd//cycle
where $c[@id]
return $c
)

Every cycle has an ID, not important here but it is a must to specify it.
What is the difference between the above use of count and the below use of count?

let $bd := doc("document")
let $c := $bd//cycle[@id]
return count($c)

I dont know the difference between these 2 XQueries return same result but following the same pattern the next 2 queries should work but the 2nd one doesnt... Here they are:

The total of hours of modules which is above 100.

*Working query*
let $bd:=doc("document")
return sum (
for $m in $bd//module[@id]
where $m/hours>100
return $m/hours
)

*Not working query*
let $bd := doc("document")
for $c in $bd//module[@id]
where $c/hours>100
return sum($c/hours)

Id like to know why following the same "pattern" the second query is not working.
The output of the not working query is this one:

160 160 256 224 192 160

Its not the result i need, I want the sum of all them.

Was it helpful?

Solution

The first two expressions are functionally equivalent. The difference is the use of FLWOR vs. XPath to select your sequence.

In the second example, you are calling sum() on each item of the sequence ($c/hours), instead of on the sequence itself:

let $bd := doc("document")
return sum(
  for $c in $bd//module[@id]
  where $c/hours>100
  return $c/hours)

You could also use XPath:

let $bd := doc("document")
let $c := $bd//module[@id][hours>100]
return sum($c/hours)

Or similarly assign the result of the FLWOR to a variable and sum that:

let $bd := doc("document")
let $c := 
  for $m in $bd//module[@id]
  where $m/hours>100
  return $m/hours
return sum($c)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top