Counting in SPARQL

ip. picture ip. · May 11, 2011 · Viewed 12.9k times · Source

Ok so i have this query

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> 

SELECT DISTINCT (COUNT(?instance) AS ?count) WHERE {
?instance a <http://dbpedia.org/ontology/Ambassador> . 
}

and the result is 286. Cool. Now I want to get the number of ambassadors that have http://dbpedia.org/property/name property. But

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> 

SELECT DISTINCT (COUNT(?instance) AS ?count) WHERE {
?instance a <http://dbpedia.org/ontology/Ambassador> . 
?instance <http://dbpedia.org/property/name> ?name
}

results in 533 :(. So it is counting more because there are people which have this property one or more times. But how do I get the number of ambassadors that have this property regardless of how many times they have it. Can you do this in a single query?

Thanks.

Answer

Jonathan picture Jonathan · May 11, 2011

You might want to try this:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> 

SELECT (COUNT(DISTINCT ?instance) AS ?count) WHERE {
?instance a <http://dbpedia.org/ontology/Ambassador>; 
          <http://dbpedia.org/property/name> ?name
}

It's giving me a result of 283, which might or might not be right :).