yayamamo
yayamamo

Reputation: 13

How to make a SPARQL query that counts unique nodes within the OPTIONAL clause

I'd like to make a SPARQL query that counts unique nodes within and without an OPTIONAL clause as follows:

SELECT (count(?o) AS ?numA) (count(DISTINCT ?o) AS ?numD) (count(?r) AS ?numO) ?UniqueCountOf_o_within_the_OPTIONAL_clause
WHERE {
  ?i ex:predicate ?o.
  OPTIONAL {
    ?o rdf:type ?r.
  }
}

Values of numA, numD, and numO can be obtained properly, but I don't have any idea of getting the unique count of ?o within the OPTIONAL clause. Is there any way of making a query, or should I separate it into two queries?

Thanks.

Upvotes: 1

Views: 575

Answers (1)

Pascalco
Pascalco

Reputation: 2826

you can copy the values of ?o in the OPTIONAL clause into a new variable ?o2 and then count the number of distinct values on ?o2.

SELECT (count(?o) AS ?numA) (count(DISTINCT ?o) AS ?numD) (count(?r) AS ?numO) (count(DISTINCT ?o2) AS ?numX) WHERE {
  ?i ex:predicate ?o.
  OPTIONAL {
    ?o rdf:type ?r.
    BIND (?o AS ?o2)
  }
}

Upvotes: 1

Related Questions