首页 > 解决方案 > SPARQL wikidata group-by:获取答案中的分组项目(具有多个城市的河流)

问题描述

以下查询返回至少有 3 个大城市的河流。

在 wikidata 查询服务上试一试

# rivers with at least 3 big cities

SELECT ?river ?riverLabel (COUNT(?city) AS ?citycount)
WHERE {
  ?river wdt:P31 wd:Q4022. # ... is a river
  ?city wdt:P31 wd:Q1549591. # ... is a big city
  ?city wdt:P206 ?river.  # ... located in or next to body of water
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]".}
}
GROUP BY ?river ?riverLabel
HAVING (?citycount >= 3)    # ← important line
ORDER BY DESC(?citycount)

如何在答案中包含实际城市(及其标签)?顺序应该保持不变,即前 13 个结果应该是位于长江的城市,接下来的 11 个结果应该是位于莱茵河的城市,等等。

标签: sparqlaggregationwikidata-query-service

解决方案


您应该尝试使用GROUP_CONCAT,见下文。

# rivers and cities
SELECT ?river ?riverLabel (COUNT(?city) AS ?citycount)
(GROUP_CONCAT(CONCAT(STR(?city), "--> ", ?cityLabel); SEPARATOR="; ") AS ?cities)
WHERE {
  ?river wdt:P31 wd:Q4022. # ... is a river
  ?city wdt:P31 wd:Q1549591. # ... is a big city
  ?city wdt:P206 ?river.  # ... located in or next to body of water
  ?city rdfs:label ?cityLabel .
  FILTER(LANG(?cityLabel) = 'en')
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]".}
}
GROUP BY ?river ?riverLabel
HAVING (?citycount >= 3)
ORDER BY DESC(?citycount)

推荐阅读