如果我理解正确,您要求找到每个类别中的最高分,然后为每个类别找到该类别中得分最高的学生。使用数据更容易(将来,请尽量提供我们可以使用的最少数据),所以这里有一些示例数据:
@prefix : <urn:ex:>
:student1 :hasScore [ :inCategory :category1 ; :value 90 ] ,
[ :inCategory :category2 ; :value 75 ] ,
[ :inCategory :category3 ; :value 85 ] .
:student2 :hasScore [ :inCategory :category2 ; :value 75 ] ,
[ :inCategory :category3 ; :value 90 ] ,
[ :inCategory :category4 ; :value 90 ] .
:student3 :hasScore [ :inCategory :category1 ; :value 85 ] ,
[ :inCategory :category2 ; :value 80 ] ,
[ :inCategory :category4 ; :value 95 ] .
有四个类别,student1在类别1中得分最高,student3在类别2和类别4中得分最高,student2在类别3中得分最高。我们可以这样写一个查询:
prefix : <urn:ex:>
select ?category ?student ?highScore where {
#-- Find the high score in each category
{ select ?category (max(?score) as ?highScore) {
?student :hasScore [ :inCategory ?category ; :value ?score ] .
}
group by ?category
}
#-- Then find the student that had that high
#-- score in the category.
?student :hasScore [ :inCategory ?category ; :value ?highScore ] .
}
--------------------------------------
| category | student | highScore |
======================================
| :category1 | :student1 | 90 |
| :category2 | :student3 | 80 |
| :category3 | :student2 | 90 |
| :category4 | :student3 | 95 |
--------------------------------------
如果您不关心哪个学生得分最高,那么您只需要那个内部子查询:
prefix : <urn:ex:>
select ?category (max(?score) as ?highScore) {
?student :hasScore [ :inCategory ?category ; :value ?score ] .
}
group by ?category
--------------------------
| category | highScore |
==========================
| :category1 | 90 |
| :category2 | 80 |
| :category3 | 90 |
| :category4 | 95 |
--------------------------
如果您使用不同的属性
在评论中,你问,
我的本体是这样的: Student1 :Englishscore 90; 物理分数 67; ChemScore 78。其他学生也一样。我应该引入一个空白节点,比如 hasScore,它引用了 Englishscore、PhyscicsScore [sic] 和 ChemScore?
首先,我建议您标准化您的命名约定。首先,一定要使用正确的拼写(例如Physics)。然后,要么缩写,要么不缩写。您将Chemistry缩写为Chem,而不是将English缩写为Eng。最后,在您的大小写上保持一致(例如,EnglishScore,而不是Englishscore)。
没有必要使用我使用的那种表示。您没有提供示例数据(请在以后提供),所以我使用了我认为相当容易使用的数据。您的表示似乎不太灵活,但您仍然可以获得所需的信息。这是一些新的示例数据:
@prefix : <urn:ex:>
:student1 :hasCat1Score 90 ;
:hasCat2Score 75 ;
:hasCat3Score 85 .
:student2 :hasCat2Score 75 ;
:hasCat3Score 90 ;
:hasCat4Score 90 .
:student3 :hasCat1Score 85 ;
:hasCat2Score 80 ;
:hasCat4Score 95 .
然后查询只需要为属性使用一个变量,该变量同时将学生与分数相关联,并指示类别。所以你仍然只是按该属性分组并要求最高分:
prefix : <urn:ex:>
select ?hasScore (max(?score) as ?highScore) {
?student ?hasScore ?score
}
group by ?hasScore
-----------------------------
| hasScore | highScore |
=============================
| :hasCat1Score | 90 |
| :hasCat2Score | 80 |
| :hasCat3Score | 90 |
| :hasCat4Score | 95 |
-----------------------------