Sparql: Arithmetic operators between variables?

2019-03-25 21:28发布

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

标签: sparql
2条回答
狗以群分
2楼-- · 2019-03-25 21:28

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 .
}
查看更多
Luminary・发光体
3楼-- · 2019-03-25 21:34

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
}
查看更多
登录 后发表回答