Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sparql: Arithmetic operators between variables?

Tags:

sparql

Hi I have a query like this:

SELECT ?a ?b
WHERE
{
?c property:name "myThing"@en
?c property:firstValue ?b
?c property:secondValue ?a
}

How can I divide the first nuber and the second? idealy somthing like this:

SELECT ?a/?b
WHERE
{
?c property:name "myThing"@en
?c property:firstValue ?b
?c property:secondValue ?a
}

Thank you

like image 651
Lince81 Avatar asked Feb 18 '11 14:02

Lince81


2 Answers

In SPARQL 1.1 you can do it using Project expressions like so:

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT (xsd:float(?a)/xsd:float(?b) AS ?result)
WHERE
{
?c property:name "myThing"@en
?c property:firstValue ?b
?c property:secondValue ?a
}

You may alternately use xsd:double(?var) to cast to a double, xsd:integer(?var) to cast to an integer and xsd:decimal(?var) to cast to a decimal.

Note that SPARQL specifies type promotion rules so for example:

  • integer / integer = decimal
  • float / double = double

If you really need the result in a guaranteed datatype you can cast the whole divide expression e.g.

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
SELECT (xsd:double(xsd:float(?a)/xsd:float(?b)) AS ?result)
WHERE
{
?c property:name "myThing"@en
?c property:firstValue ?b
?c property:secondValue ?a
}
like image 99
RobV Avatar answered Oct 02 '22 23:10

RobV


There are two ways to achieve this:

SELECT ((?a/?b) AS ?result) WHERE {
    ?c property:name "myThing"@en .
    ?c property:firstValue ?b .
    ?c property:secondValue ?a .
}

or

SELECT ?result WHERE {
    BIND((?a/?b) AS ?result) .
    ?c property:name "myThing"@en .
    ?c property:firstValue ?b .
    ?c property:secondValue ?a .
}
like image 29
Guy Needham Avatar answered Oct 03 '22 00:10

Guy Needham