SPARQL Aggregation
Also GROUP BY (SPARQL)
`GROUP BY ?g1 … ?gm` partitions the rows matched by a SPARQL WHERE clause by the values of the grouping variables, and the SELECT returns one row per group in which every other variable is aggregated, e.g. `(COUNT(?x) AS ?n)`, or left out.
Properties#
- Every selected variable is grouped or aggregated. A variable that is not in
GROUP BY(like?paper) has many values per group. It must either be left out of theSELECTor appear inside an aggregate. - That is why the lecture’s query groups by
?venue ?nameand not just?venue:?nameis selected. If every venue has exactly one label, both give the same groups. - The aggregate is a new variable and can be used afterwards, e.g. in
ORDER BY DESC(?num_papers)(Ordering).
Sub-SELECT. A complete SELECT … WHERE { … } GROUP BY … in braces can stand inside a WHERE clause. Its result table is joined with the other patterns of the outer query via their shared variables, like a Subquery in SQL’s FROM.
- Aggregate first, then join. In the lecture, the inner query counts papers per venue, and the outer query adds
?venue rdfs:label ?nameafterwards. The result is the same as with the flat query, but cheaper: the label is joined once per venue, instead of once per paper before grouping. - Inside the sub-SELECT, only the variables in its
SELECT(here?venue,?num_papers) are visible to the outer query.
Example#
Toy data: papers in venue , paper in venue , each venue with one label.
SELECT ?venue ?name (COUNT(?paper) AS ?num_papers) WHERE {
?paper dblp:publishedInStream ?venue .
?venue rdfs:label ?name .
}
GROUP BY ?venue ?name
ORDER BY DESC(?num_papers)
The WHERE clause gives 3 rows , , . Grouping gives , .
Sub-SELECT variant (Slide 22):
SELECT ?venue ?name ?num_papers WHERE {
{
SELECT ?venue (COUNT(?paper) AS ?num_papers) WHERE {
?paper dblp:publishedInStream ?venue .
} GROUP BY ?venue
}
?venue rdfs:label ?name .
}
ORDER BY DESC(?num_papers)
The inner query gives , . Only these 2 rows are joined with the labels, instead of the 3 paper rows.
Sources#
- Slides 01, p. 21 (GROUP BY, COUNT, rule for non-grouped variables), p. 22 (sub-SELECT)
- ADIS_VL01 > GROUP BY and Aggregation, ADIS_VL01 > Sub-SELECT