SPARQL:如何将多个字段分组?

huangapple go评论51阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月8日 19:16:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定