SPARQL 中的 GROUP 和 COUNT
GROUP and COUNT in SPARQL
我正在使用 WikiData SPARQL Endpoint 搜索两个实体:博物馆 (wd:Q33506
) 和图书馆 (wd:Q7075
),它们拥有 instagram 和 Twitter 帐户以及它们来自哪个国家/地区。我正在尝试对它们进行计数并按国家/地区对它们进行分组。
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
主要错误是:
Query is malformed: Bad aggregate
来自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.
因此,您的查询应该是:
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)
我还在投影中添加了 UNION
、DISTINCT
并将 ?country
替换为 ?item
。
请注意,同时拥有 Instagram 和 Twitter 帐户的图书馆和博物馆也被计算在内。
我正在使用 WikiData SPARQL Endpoint 搜索两个实体:博物馆 (wd:Q33506
) 和图书馆 (wd:Q7075
),它们拥有 instagram 和 Twitter 帐户以及它们来自哪个国家/地区。我正在尝试对它们进行计数并按国家/地区对它们进行分组。
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
主要错误是:
Query is malformed: Bad aggregate
来自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.
因此,您的查询应该是:
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)
我还在投影中添加了 UNION
、DISTINCT
并将 ?country
替换为 ?item
。
请注意,同时拥有 Instagram 和 Twitter 帐户的图书馆和博物馆也被计算在内。