Peter Krauss
Peter Krauss

Reputation: 13982

How to count items with some property

Using https://query.wikidata.org I need to count the number of Q* items of Wikidata that have a statement with P402. Something like

SELECT (COUNT(?item) AS ?count) WHERE {?item wdt:P402.}

but, of course, it is an invalid query.

Upvotes: 0

Views: 689

Answers (1)

Jeen Broekstra
Jeen Broekstra

Reputation: 22052

Your WHERE clause does not specify a valid basic triple pattern: an RDF triple consists of three items (subject, predicate, and object), where your pattern only contains two. Not knowing the Wikidata vocabulary too well, I'll assume that wdt:P402 is the predicate you're interested in. If that is case, your pattern is missing a variable or placeholder for the object of the triple pattern.

To fix this, you could do something like this:

SELECT (COUNT(?item) AS ?count) WHERE {?item wdt:P402 ?object.}

Or (since you're not really interested in the value of the object), use a blank node instead:

SELECT (COUNT(?item) AS ?count) WHERE {?item wdt:P402 [].}

Finally, if you want to make sure that items which have more than one value for this property do not get counted more than once, you also need to add a DISTINCT clause to your query:

SELECT (COUNT(DISTINCT ?item) AS ?count) WHERE {?item wdt:P402 [].}

Upvotes: 3

Related Questions