Search code examples
sparqlrdftriplestore

Filter projected expressions in SPARQL


Here is en example query:

PREFIX  dc:  <http://purl.org/dc/elements/1.1/> 
PREFIX  ns: <http://example.org/ns#> 
SELECT  ?title (?p AS ?fullPrice) (?fullPrice*(1-?discount) AS ?customerPrice) 
WHERE {
  ?x ns:price ?p .    
  ?x dc:title ?title .     
  ?x ns:discount ?discount
}

The results would be:

| title              | fullPrice | customerPrice |
| "The Semantic Web" |        23 |         17.25 |
| "SPARQL Tutorial"  |        42 |         33.6  |

I want only customerPrice > 20 to be displayed.

I tried HAVING (?customerPrice > 20) at the end of the query but it seems not to see projected expressions.

Any other way to do this?


Solution

  • Move the calculated variable from the SELECT list into a BIND clause inside the query pattern. Then you can use FILTER on the variable:

    SELECT ?title ?fullPrice ?customerPrice
    WHERE {
        ?x ns:price ?fullPrice.
        ?x dc:title ?title.
        ?x ns:discount ?discount
        BIND (?fullPrice * (1-?discount) AS ?customerPrice)
        FILTER (?customerPrice > 20)
    }