Sparql: Arithmetic operators between variables?
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 som开发者_StackOverflow中文版thing like this:
SELECT ?a/?b
WHERE
{
?c property:name "myThing"@en
?c property:firstValue ?b
?c property:secondValue ?a
}
Thank you
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
}
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 .
}
精彩评论