iMBLISH
iMBLISH

Reputation: 65

SPARQL average instances

Is there any way to find the average, min, and max number of instances per class? I have found this:

SELECT (count(?instance) as ?no) 
WHERE {
    ?instance a ?class .
}
group by ?class
order by desc(?no)    

Upvotes: 2

Views: 3641

Answers (1)

UninformedUser
UninformedUser

Reputation: 8465

You are almost there.

Your current query returns the number of instances per class, e.g.

+-------+
|  no   |
+-------+
| 33054 |
| 64239 |
| 28675 |
+-------+

Now, what you want is to compute come aggregates on this intermediate results. Fortunately, SPARQL 1.1 allows for sub-queries, i.e. we can directly reuse the result of your query inside another query and simply use the corresponding aggregate functions:

SELECT (AVG(?no) AS ?avg) 
       (MIN(?no) AS ?min) 
       (MAX(?no) AS ?max) 
WHERE { 
 SELECT (COUNT(?instance) AS ?no) 
 WHERE { ?instance rdf:type ?class }
 GROUP BY ?class 
}

Output:

+-----------------------+-------+-------+
|          avg          |  min  |  max  |
+-----------------------+-------+-------+
| 41989.333333333333333 | 28675 | 64239 |
+-----------------------+-------+-------+

Note, I removed the ORDER BY as it wouldn't contribute to the final result here. In addition, you can see that no GROUP BY is necessary as we're computing the aggregates on the only existing column.

Upvotes: 4

Related Questions