Sparql: Arithmetic operators between variables?

北城以北 提交于 2019-12-21 04:13:08

问题


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


回答1:


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
}



回答2:


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 .
}


来源:https://stackoverflow.com/questions/5042624/sparql-arithmetic-operators-between-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!