How to select first N row of each group

2019-07-14 01:31发布

I have some data in my triple store like:

Subject     Predicate                               Object
-----------------------------------------------------------------------------------
<http://Doc1>        http://purl.org/dc/terms/created       2013                   
<http://Doc1>        http://purl.org/dc/terms/contributor   John                
.
.
<http://Doc2>       http://purl.org/dc/terms/created        2014
<http://Doc2>        http://purl.org/dc/terms/contributor    David
.
.
<http://Doc3>       http://purl.org/dc/terms/created        2013
<http://Doc3>       http://purl.org/dc/terms/contributor    John        
.
.
.

I want to select every triple where subject is Doc1:

SELECT ?subject ?predicate ?object
WHERE {
    ?subject ?predicate ?object
    FILTER ( ?subject = <http://Doc1> )
}

That was easy! This is my output:

Subject     Predicate                               Object
-----------------------------------------------------------------------------------
<http://Doc1>        http://purl.org/dc/terms/created       2013                   
<http://Doc1>       http://purl.org/dc/terms/contributor    John    
..          

And now for each object i want to return first N triples. In fact I want to select N triples where some document was created in 2013 and N triples where contributor is John etc. I tried to do something like:

SELECT ?subject ?predicate ?specObject
WHERE {
    <http://Doc1> ?predicate ?specObject.
     ?subject ?predicate ?specObject
}

But this query returns every triple where object is 2013 and John. I need just first five triple for each group. How can I build this query? Thanks!

0条回答
登录 后发表回答