Search code examples
limitsparqlsemantic-web

SPARQL limit only a specific variable in a result triple


I try to get a SPARQL result with only the highest variable for a triple combination.

Ok, let's try to explain it.

Let's say we got something like this:

:resource1 pred:hasQuality :UltraQuality
:resource2 pred:hasQuality :MediumQuality
:resource2 pred:hasQuality :LowQuality
:resource3 pred:hasQuality :UltraQuality
:resource3 pred:hasQuality :LowQuality
:resource4 pred:hasQuality :LowQuality

Now, I want to get all resources with there highest quality. The quality could be ordered with ORDER BY or MAX. (L->M->U).

I tried a lot like this:

SELECT ?res ?qual
WHERE {
    ?res pred:hasQuality ?qual.
}
ORDER BY ?res DESC(?qual)

But now, if there are more than one triple for the same ?res, I want to eliminate the other ones.

The expected result should be:

:resource1 :UltraQuality
:resource2 :MediumQuality
:resource3 :UltraQuality
:resource4 :LowQuality

Solution

  • You want to group by the items, which provides you with a set of qualities for each item. From that item, you want to take the maximum value. Suppose you've got this data:

    @prefix : <http://stackoverflow.com/q/20562673/1281433/>
    
    :a :quality 3 .
    :a :quality 4 .
    :a :quality 5 .
    
    :b :quality 9 .
    
    :c :quality 2 .
    :c :quality 1 .
    

    Then you can use a query like this:

    prefix : <http://stackoverflow.com/q/20562673/1281433/>
    
    select ?item (max(?quality) as ?maxQuality)
    where {
      ?item :quality ?quality .
    }
    group by ?item
    

    You'll get these results:

    ---------------------
    | item | maxQuality |
    =====================
    | :b   | 9          |
    | :c   | 2          |
    | :a   | 5          |
    ---------------------