How to use .sum() with triples property X values of documents with class Y (not onlye JS-arrays)?

Ctrl+F ’ sum’

How to use .sum() with triples property X values of documents with class Y (not onlye JS-arrays)?

Ctrl+F ’ sum’

1 Like

In the javascript client:

```
and(group_by([], "v:Z", "v:List")
.and(triple("v:X", "rdf:type", "scm:BankAccount"),
triple("v:X", "scm:balance", "v:Z")),
sum("v:List", "v:Sum"))
```

Group by allows you to group on a list of variables to make unique (in this case degenerate) “v:Z” is the variable to group, “v:List” is the final grouping and then we attach the relevant query with a dot. We can then take the resulting list and use “sum” to sum the values.

Thanks, it works!

Version with a clearer indentation:

```
and(
group_by([], "v:Z", "v:List").and(
triple("v:X", "rdf:type", "scm:BankAccount"),
triple("v:X", "scm:balance", "v:Z")
),
sum("v:List", "v:Sum")
)
```

Second question is how to use the result of sum for next calculation? For example, to divide one sum to second sum.

Documentation links are preferred, if available

My version of the code didn’t work:

```
let [ result ] = vars('my_result')
and(
group_by([], "v:Z", "v:List").and(
triple("v:X", "rdf:type", "scm:BankAccount"),
triple("v:X", "scm:balance", "v:Z")
),
evaluate(divide(sum("v:List", "v:Sum"), 100), result)
)
```

It returns some error:

```
Query Failed (0.311 seconds)
Syntax error found
```

I can see how that might be confusing, but `sum`

is not actually an arithmetic operation but a WOQL word. The following should work:

```
let [ result ] = vars('my_result')
and(
group_by([], "v:Z", "v:List").and(
triple("v:X", "rdf:type", "scm:BankAccount"),
triple("v:X", "scm:balance", "v:Z")
),
sum("v:List", "v:Sum"),
evaluate(divide("v:Sum", 100), result)
)
```