Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP and COUNT in SPARQL

I am using WikiData SPARQL Endpoint to search for two entities: museums (wd:Q33506) and libraries (wd:Q7075) that have instagram and twitter accounts and from which country they are from. I am trying to count them and group them by country.

SELECT ?item ?instagram ?twitter ?countryLabel (COUNT(?country) AS ?ccount) WHERE {
  { ?item (wdt:P31/wdt:P279*) wd:Q33506. }
  { ?item (wdt:P31/wdt:P279*) wd:Q7075. }
  ?item wdt:P2003 ?instagram.
  ?item wdt:P2002 ?twitter.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
  OPTIONAL { ?item wdt:P17 ?country. }
}
GROUP BY ?country
ORDER BY ?ccount
like image 884
Trinker Avatar asked Oct 23 '25 08:10

Trinker


1 Answers

The main error is:

Query is malformed: Bad aggregate

From 11.4 Aggregate Projection Restrictions:

In a query level which uses aggregates, only expressions consisting of aggregates and constants may be projected, with one exception. When GROUP BY is given with one or more simple expressions consisting of just a variable, those variables may be projected from the level.

Thus, your query should be:

SELECT ?countryLabel (COUNT(DISTINCT ?item) AS ?ccount) WHERE {
  { ?item wdt:P31/wdt:P279* wd:Q33506. }
  UNION
  { ?item wdt:P31/wdt:P279* wd:Q7075. }
  ?item wdt:P2003 ?instagram.
  ?item wdt:P2002 ?twitter.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
  OPTIONAL { ?item wdt:P17 ?country. }
}
GROUP BY ?countryLabel ORDER BY DESC(?ccount)

Try it!

I've also added UNION, DISTINCT and replaced ?country with ?item in the projection.

Note that libraries and museums that have both Instagram and Twitter accounts are counted.

like image 178
Stanislav Kralin Avatar answered Oct 26 '25 10:10

Stanislav Kralin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!