PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX tabular: <http://ua.be/sdo2l/vocabulary/base/tabular#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX afn: <http://jena.apache.org/ARQ/function#>


SELECT ?table ?content
WHERE {
  ?table rdf:type tabular:TabularData .
  ?table owl:sameAs <http://ua.be/drivetrain/description/artifacts/artifacts#drivetrain-sensor-data-v1> .
  ?table tabular:hasRows ?header .
  ?header rdf:type tabular:HeaderRow .
  ?header tabular:hasCell ?headerCell .
  ?headerCell tabular:holdsContent "sense_00" .
  ?headerCell tabular:hasColumnPosition ?cPos .
  ?table tabular:hasRows ?rows .
  ?rows rdf:type tabular:Row .
  ?rows tabular:hasHeadingModifier "no" .
  ?rows tabular:hasCell ?cells .
  ?cells tabular:hasColumnPosition ?cPos.
  ?cells tabular:holdsContent ?content .
  {
  SELECT ?table ?avg ?count ( afn:sqrt( sum( ((xsd:double(?content)) - ?avg) * ((xsd:double(?content)) - ?avg) ) / (?count - 1) ) as ?stddev )
  WHERE {
    ?table rdf:type tabular:TabularData .
    ?table owl:sameAs <http://ua.be/drivetrain/description/artifacts/artifacts#drivetrain-sensor-data-v1> .
  	?table tabular:hasRows ?header .
    ?header rdf:type tabular:HeaderRow .
    ?header tabular:hasCell ?headerCell .
    ?headerCell tabular:holdsContent "sense_00" .
    ?headerCell tabular:hasColumnPosition ?cPos .
    ?table tabular:hasRows ?rows .
    ?rows rdf:type tabular:Row .
    ?rows tabular:hasHeadingModifier "no" .
    ?rows tabular:hasCell ?cells .
    ?cells tabular:hasColumnPosition ?cPos.
    ?cells tabular:holdsContent ?content .
    {
      SELECT ?table (avg(xsd:double(?content)) as ?avg) (count(*) as ?count)
      WHERE {
  	    ?table rdf:type tabular:TabularData .
      	?table owl:sameAs <http://ua.be/drivetrain/description/artifacts/artifacts#drivetrain-sensor-data-v1> .
  	    ?table tabular:hasRows ?header .
      	?header rdf:type tabular:HeaderRow .
      	?header tabular:hasCell ?headerCell .
       	?headerCell tabular:holdsContent "sense_00" .
      	?headerCell tabular:hasColumnPosition ?cPos .
        ?table tabular:hasRows ?rows .
        ?rows rdf:type tabular:Row .
        ?rows tabular:hasHeadingModifier "no" .
        ?rows tabular:hasCell ?cells .
        ?cells tabular:hasColumnPosition ?cPos.
        ?cells tabular:holdsContent ?content .
      }
      GROUP BY ?table
    }
  }
  GROUP BY ?table ?avg ?count
  }
}
HAVING ((abs((xsd:double(?content))-?avg)/?stddev) >= 2 )



