英文:
SPARQL: How can I group multiple fields?
问题
我试图使用GROUP BY和GROUP_CONCAT函数将我的结果分组为每个实体的单行,但我无法使其工作。
这是我有的内容:一个项目有一个名称,可以有多个主题和领域。
当我执行此查询时:
SELECT ?proj ?name ?topic ?area
WHERE {
?proj hasName ?name .
?proj hasTopic ?topic .
?proj hasArea ?area .
}
我得到以下绑定表格:
proj | name | topic | area |
---|---|---|---|
uri | My Project | building | Europe |
uri | My Project | building | Asia |
uri | My Project | park | Europe |
uri | My Project | park | Asia |
但我想要的是:
proj | name | topic | area |
---|---|---|---|
uri | My Project | building, park | Europe, Asia |
我尝试过使用:
SELECT ?proj ?name
(GROUP_CONCAT(?topic; separator=", ") AS ?topics)
(GROUP_CONCAT(?area; separator=", ") AS ?areas)
WHERE {
?proj hasName ?name .
?proj hasTopic ?topic .
?proj hasArea ?area .
}
GROUP BY ?proj ?name
但主题重复了:building, building, park, park
。
我漏掉了什么?我应该如何处理这个问题?
非常感谢!
英文:
I'm trying to use the GROUP BY and GROUP_CONCAT functions to group my results into single rows for each entity but I cannot make it work.
This is what I have: a Project has a Name and can have multiple Topics and Areas.
When I do this query:
SELECT ?proj ?name ?topic ?area
WHERE {
?proj hasName ?name .
?proj hasTopic ?topic .
?proj hasArea ?area .
}
I get this table of bindings:
proj | name | topic | area |
---|---|---|---|
uri | My Project | building | Europe |
uri | My Project | building | Asia |
uri | My Project | park | Europe |
uri | My Project | park | Asia |
But what I would want is:
proj | name | topic | area |
---|---|---|---|
uri | My Project | building, park | Europe, Asia |
I've tried using:
SELECT ?proj ?name
(GROUP_CONCAT(?topic; separator=", ") AS ?topics)
(GROUP_CONCAT(?area; separator=", ") AS ?areas)
WHERE {
?proj hasName ?name .
?proj hasTopic ?topic .
?proj hasArea ?area .
}
GROUP BY ?proj ?name
But I get the topics doubled: building, building, park, park
.
What am I missing? How should I approach this?
Thanks a lot in advance
答案1
得分: 2
你走在正确的道路上,但你只需要使用DISTINCT
关键字。以下对我有效。
SELECT ?proj ?name
(GROUP_CONCAT(DISTINCT ?topic; separator=" , ") AS ?topics)
(GROUP_CONCAT(DISTINCT ?area; separator=" , ") AS ?areas)
WHERE {
?proj hasName ?name .
?proj hasTopic ?topic .
?proj hasArea ?area .
}
GROUP BY ?proj ?name
英文:
You are on the right path, but you just need to use the DISTINCT
keyword. The following works for me.
SELECT ?proj ?name
(GROUP_CONCAT(DISTINCT ?topic; separator=", ") AS ?topics)
(GROUP_CONCAT(DISTINCT ?area; separator=", ") AS ?areas)
WHERE {
?proj hasName ?name .
?proj hasTopic ?topic .
?proj hasArea ?area .
}
GROUP BY ?proj ?name
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论