Accumulated sum in SPARQL

本秂侑毒 提交于 2019-12-24 07:26:32

问题


Do we have a way to make an accumulated sum in SPARQL that is not reduced?

For instance,

SELECT ?p WHERE {
  VALUES ?p { 1 1 2 }
}
ORDER BY ?p

would result in 1 2 4, - rather than 4.


回答1:


If you want to calculate accumulated sums in the absense of RDF data ('FROM DUAL'), it is impossible:

  • SPARQL list syntax is not allowed in VALUES,
  • VALUES themself are unordered.

However, if values are present in RDF data, it is possible to calculate their accumulated sums.

Consider the following example.

Input data

INSERT DATA {
  ex:st ex:order "1"^^xsd:integer ;
        ex:value "1"^^xsd:integer .     
  ex:nd ex:order "2"^^xsd:integer ;
        ex:value "1"^^xsd:integer .
  ex:rd ex:order "3"^^xsd:integer ;
        ex:value "2"^^xsd:integer .
}

Query

SELECT
(SAMPLE(?v1) AS ?v)
(SUM(?v2) AS ?acc)
WHERE {
  ?e1 ex:order ?o1 ; ex:value ?v1 .
  ?e2 ex:order ?o2 ; ex:value ?v2 .
  FILTER (?o1 >= ?o2)
} GROUP BY ?e1 ORDER BY ASC(SAMPLE(?o1))

Output

  v                   acc               
 ------------------- ------------------ 
  "1"^^xsd:integer    "1"^^xsd:integer  
  "1"^^xsd:integer    "2"^^xsd:integer  
  "2"^^xsd:integer    "4"^^xsd:integer  

The values in the example above are ordered explicetely, but it is not very hard to write a query when values are ordered implicitely (as in ABC analysis).


Let us consider another example, which uses Turtle list syntax.

Input data

INSERT DATA {
  ex:data ex:values (1 1 2)
}

Query

SELECT
(SAMPLE(?v2) AS ?v)
(SUM(?v1) AS ?acc)
WHERE { 
  ex:data ex:values/rdf:rest* ?e1 .
                              ?e1 rdf:first ?v1 .
                              ?e1 rdf:rest* ?e2 .
                              ?e2 rdf:first ?v2 .
} GROUP BY (?e2) ORDER BY(COUNT(?e1))

Output

  v                   acc               
 ------------------- ------------------ 
  "1"^^xsd:integer    "1"^^xsd:integer  
  "1"^^xsd:integer    "2"^^xsd:integer  
  "2"^^xsd:integer    "4"^^xsd:integer  


来源:https://stackoverflow.com/questions/44440966/accumulated-sum-in-sparql

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